<?php
namespace Admin\Frontend\Controllers;

use Admin\Models\cost\CostCharge;
use Admin\Models\overt\XhovertAreainfo;
use Admin\Models\user\XhsysUserHistory;
use Helpers\Device;
use Helpers\Tool;
use Helpers\Main;
use Helpers\Assets;
use Helpers\Template;
use Helpers\User;
use Helpers\XhException;
use Modules\Charge;
use Modules\Power;
use Modules\School;
use Services\UserService;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\user\XhsysUser;
use Admin\Models\user\XhsysUserstud;
use Admin\Models\cost\XhcostStudcharge;
use Admin\Models\cost\CostChargeFlow;
use Admin\Models\cost\CostChargeDetail;
use Admin\Models\user\XhsysUserPayVoucher;

class CostController extends ControllerBase
{

    private static $payVoucherState = [
        1 => '待审核',
        2 => '通过',
        3 => '未通过',
    ];
    private function getYearEnum()
    {
        $nowYear = date('Y');
//        $yearArr = ['' => '-年份-'];
        $yearArr = [];
        for ($year = $nowYear - 2; $year <= $nowYear + 1; $year++) {
            $yearArr[$year] = $year;
        }
        return $yearArr;
    }

    /**
     * 收费页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180912
     */
    public function chargeAction()
    {
        $this->view->pick('cost/charge');
        Main::showNavPosition();
        Assets::easyUI('js/cost/charge.js');
        if (!Power::exist('Cost_Charge')) {
            return $this->sendViewError('无查看此页面权限');
        }

        //学校工具栏
        $schSearchArr = $schButtonArr = $studButtonArr = $studSearchArr = [];
        $schSearchArr[] = ['type'=>'select', 'id'=>'list_school_status', 'multiple' => 'true',
            'data' => School::$enum['iStatus'], 'style' => 'width: 100px'];
        $schSearchArr[] = ['type' => 'text', 'id' => 'list_school_vague', 'label' => ' 搜索：'];
        $schSearchArr[] = ['type' => 'button', 'id' => 'bt_list_school_search', 'text' => ' 查找',
            'icon' => 'fa-search'];
        if (Power::exist('chargeTotal_Code')) {
            $schButtonArr[] = ['id' => 'bt_sch_code', 'text' => '更改编号', 'icon' => 'fa-pencil'];
        }

        //学生搜索条件
        $studSearchArr[] = ['type' => 'select', 'id' => 'list_stud_history', 'style' => 'width: 60px;', 'data' => [
            -1 => '全部',
            0 => '正常',
            1 => '历史'
        ]];
        $studSearchArr[] = ['type' => 'select', 'id' => 'list_stud_year', 'style' => 'width:60px;',
            'data' => $this->getYearEnum(), 'default' => date('Y')];
        $studSearchArr[] = ['type'=>'select', 'id'=>'list_payVoucher_status',
            'data' => [0 => '缴费凭证'] + self::$payVoucherState, 'style' => 'width: 80px'];
        $studSearchArr[] = ['type' => 'select', 'id' => 'list_stud_charge', 'style' => 'width:75px;', 'data' => [
            0 => '全部',
            1 => '已缴费',
            2 => '未缴费',
            3 => '未缴全',
            4 => '无需缴费',
            5 => '异常缴费',
        ]];

        $studSearchArr[] = ['type' => 'text', 'id' => 'list_stud_vague', 'label' => ' 姓名/账号：','style' => 'width:100px !important;'];
        $studSearchArr[] = ['type' => 'text', 'id' => 'list_stud_class', 'label' => ' 班级：',
            'style' => 'width:100px !important;'];
        $studSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_startTime',
            'label' => ' 创建时间: ', 'style' => 'width:100px !important;'];
        $studSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_endTime',
            'label' => '~', 'style' => 'width:100px !important;'];
        $studSearchArr[] = ['type' => 'button', 'id' => 'bt_list_stud_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $studSearchArr[] = ['type' => 'button', 'id' => 'bt_list_stud_export', 'text' => '导出',
            'icon' => 'fa-file-excel-o', 'style' => 'margin-left:10px'];
        if (Power::exist('School_List_Stud_CheckPayVou')) {
            $studButtonArr[] = ['id' => 'bt_list_checkPayVoucher', 'text' => '审核缴费凭证', 'plain' => 'true', 'icon' => 'fa-check-square-o'];
        }
        if (Power::exist('chargeDetail_Add')) {
            $studButtonArr[] = ['id' => 'bt_list_importDetail', 'text' => '应缴导入', 'icon' => 'fa-file-excel-o'];
            $studButtonArr[] = ['id' => 'bt_list_time_adjustment', 'text' => '调整服务时间', 'icon' => 'fa-pencil'];
        }
        if (Power::exist('Cost_Charge_JournalImport')) {
            $studButtonArr[] = ['id' => 'bt_list_importFlow', 'text' => '账号导入',
                'icon' => 'fa-file-excel-o'];
        }
        if (Power::exist('Cost_Charge_HandImport')) {
            $studButtonArr[] = ['id' => 'bt_list_importNameFlow', 'text' => '姓名导入', 'icon' => 'fa-file-excel-o'];
        }
        return $this->view->setVars([
            'SchoolList' => Template::createList('schoolList', 'Cost_School', [
//                'checkbox' => false,
                'searchToolbar' => Template::createSearchToolBar($schSearchArr, !!$schButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($schButtonArr)
            ]),
            'StudList' => Template::createList('studList', 'Cost_Charge', [
                'searchToolbar' => Template::createSearchToolBar($studSearchArr, !!$studButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($studButtonArr)
            ]),
        ]);
    }

    /**
     * 获取学校列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181026
     */
    public function getSchoolsAction()
    {
        $vague  = $this->request->getPost('vague', 'string');
        $status = $this->request->getPost('status', 'int');
        try {
            if (is_array($status)) {
                foreach ($status as $key => $val) {
                    if (!is_numeric($val)) {
                        unset($status[$key]);
                    }
                }
            }
            $params = [
                'columns' => 'iSchoolId,sSchoolName,sCode',
                'conditions' => 'bDelete = 0'
            ];
            if ($status) {
                $params['conditions'] .= ' AND iStatus IN ({status:array})';
                $params['bind']['status'] = $status;
            }
            if ($vague) {
                $params['conditions'] .= Main::runVagueCondition(['iSchoolId', 'sSchoolName', 'sCode'], $vague);
            }
            //处理学校权限
            $schoolIds = School::getPower();
            if (!$schoolIds) {
                return $this->sendDataGridError('无学校权限');
            } elseif ($schoolIds !== true) {
                $params['conditions'] .= ' AND iSchoolId IN ({schoolIds:array})';
                $params['bind']['schoolIds'] = $schoolIds;
            }

            $data = Main::runModelPage('\\Admin\\Models\\school\\XhschoolInfo', $params);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取收费信息
     *
     * @param bool $return
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by ck 20180912
     * modify by ck 20180929
     * modify by ck 20181026    增加学校id判断
     * modify by zqk 20181210   添加缴费凭证筛选条件
     */
    public function getChargeAction($return = false)
    {
        $year     = $this->request->get('year', 'string');
        $schoolId = $this->request->get('schoolId', 'int');
        $history  = $this->request->get('history', 'int', 0);
        $vague    = $this->request->get('vague', 'string');
        $className= $this->request->get('className', 'string');
        $startTime= $this->request->get('startTime', 'string');
        $endTime  = $this->request->get('endTime', 'string');
        $charge   = $this->request->get('charge', 'int');
        $payStatus   = $this->request->get('payStatus', 'int');
        try {
            if (!Power::exist('Cost_Charge')) {
                throw new \Exception('无权限', 403);
            }
            if (!$schoolId) {
                throw new \Exception('缺少学校id', 400);
            }
            if (!in_array($history, [0, 1, -1])) {
                throw new \Exception('学生状态错误', 400);
            }
            if (!$year) {
                throw new \Exception('缺少年份信息', 400);
            }
            if (!School::hasPower($schoolId)) {
                throw new \Exception('无该学校权限', 403);
            }
            if ($history == 0 or $history == 1) {
                $condition = "u.iUserType = 1 AND u.iSchoolId = {$schoolId} AND u.bDelete = 0 AND u.bHistory = {$history}";
            } else {
                $condition = "u.iUserType = 1 AND u.iSchoolId = {$schoolId} AND u.bDelete = 0";
            }
            if ($vague) {
                $condition .= Main::runVagueCondition(['u.sUserName', 'u.sLogonName'], $vague);
            }
            if ($className) {
                $condition .= Main::runVagueCondition(['u.sAdClsName'], $className);
            }
            if ($startTime) {
                $condition .= " AND u.tCreateDate >= '{$startTime}'";
            }
            if ($endTime) {
                $endTime = Tool::getEndTime($endTime, false);
                $condition .= " AND u.tCreateDate < '{$endTime}'";
            }
            switch ($charge) {
                case 1:
                    $condition .= ' AND c.receivable = c.received AND c.receivable > 0';
                    break;
                case 2:
                    $condition .= ' AND c.receivable > 0 AND c.received = 0';
                    break;
                case 3:
                    $condition .= ' AND c.receivable > c.received AND c.received > 0';
                    break;
                case 4:
                    $condition .= ' AND IFNULL(c.receivable, 0) = 0 AND IFNULL(c.received, 0) = 0';
                    break;
                case 5:
                    $condition .= ' AND c.receivable < c.received';
                    break;
            }

            if (in_array($payStatus, array_keys(self::$payVoucherState))) {
                $uids = XhsysUserPayVoucher::find([
                    'columns' => 'iUserId',
                    'conditions' => 'bDelete = 0 AND iState = '.$payStatus.' AND iChargeYear = '.$year,
                ])->toArray();
                $uids = array_unique(array_column($uids, 'iUserId'));
            }

            $builder = $this->modelsManager->createBuilder()
                ->columns('u.iUserId,u.sUserName,u.sLogonName,u.sAdClsName,u.sIdentityCode,u.bEbook,u.tCreateDate,
                        c.id,c.year,c.receivable,c.received,c.chargeNum,c.completeNum,c.flowNum,s.iExpireTime,
                        s.sMotherName,u.sMotherPhone,s.sFatherName,u.sFatherPhone,s.sOtherName,u.sOtherPhone,p.iState')
                ->addFrom('Admin\Models\user\XhsysUser', 'u')
                ->leftJoin('Admin\Models\user\XhsysUserstud', 'u.iUserId = s.iUserId', 's')
                ->leftJoin('Admin\Models\user\XhsysUserPayVoucher', 'p.iUserId = u.iUserId AND p.iChargeYear ='.$year, 'p')
                ->leftJoin('Admin\Models\cost\CostCharge', "u.iUserId = c.userId AND c.year = '{$year}'", 'c')
                ->where($condition);
            if (isset($uids)) {
                $builder->inWhere('u.iUserId', $uids);
            }
            $data = Main::runBuilderPage($builder, Charge::$enum);

            $pageReceivable = array_sum(array_column($data['rows'], 'receivable'));
            $pageReceived = array_sum(array_column($data['rows'], 'received'));

            Tool::runTimestamp($data['rows'], ['iExpireTime'], true, 'Y-m-d');
            if ($return) {
                return $data['rows'];
            }
            foreach ($data['rows'] as &$rows) {
                if (empty($rows['iState'])) {
                    $rows['iStateName'] = '<span>无</span>';
                } else {
                    if ($rows['iState'] ==1) {
                        $rows['iStateName'] = '<span>'.self::$payVoucherState[1].'</span>';
                    } elseif ($rows['iState'] == 3) {
                        $rows['iStateName'] = '<span>'.self::$payVoucherState[3].'</span>';
                    } else {
                        $rows['iStateName'] = '<span>'.self::$payVoucherState[2].'</span>';
                    }
                }

                $deviceNumber = XhsysUser::getUserInfoById($rows['iUserId'])['sDeviceNumber'];
                $signData = Device::getSignInData([['userId' => $rows['iUserId'], 'deviceNumber' => $deviceNumber]])[$rows['iUserId']];
                $rows['iSignInStatus'] = $signData['iStatus'] == 1 || $signData['iStatus'] == 2 ? "<span>是</span><div class='none'>{$signData['signatureUrl']}</div>" : '否';

                if ($rows['received'] == $rows['receivable']) {
                    if ($rows['receivable'] == 0) {
                        continue;
                    }
                    $class = 'grid-cell-text-bg-green';
                } elseif ($rows['received'] < $rows['receivable']) {
                    $class = 'grid-cell-text-bg-yellow';
                } else {
                    $class = 'grid-cell-text-bg-red';
                }
                $rows['received'] = "<div class='{$class}'>{$rows['received']}</div>";
            }

            unset($rows);

            $builder = $this->modelsManager->createBuilder()
                ->columns('c.id,c.year,c.receivable,c.received,c.chargeNum,c.completeNum,c.flowNum')
                ->addFrom('Admin\Models\user\XhsysUser', 'u')
                ->leftJoin('Admin\Models\user\XhsysUserstud', 'u.iUserId = s.iUserId', 's')
                ->leftJoin('Admin\Models\user\XhsysUserPayVoucher', 'p.iUserId = u.iUserId AND p.iChargeYear ='.$year, 'p')
                ->leftJoin('Admin\Models\cost\CostCharge', "u.iUserId = c.userId AND c.year = '{$year}'", 'c')
                ->where($condition);
            if (isset($uids)) {
                $builder->inWhere('u.iUserId', $uids);
            }
            $cost = $builder->getQuery()->execute();
            $allReceived = $allReceivable = 0;
            if ($cost) {
                $cost = $cost->toArray();
                $allReceived = array_sum(array_column($cost, 'received'));
                $allReceivable = array_sum(array_column($cost, 'receivable'));
            }

            $data['footer'] = [
                0 => ['year' => '当前', 'receivable' => "$pageReceivable", 'received' => "$pageReceived"],
                1 => ['year' => '全部', 'receivable' => "$allReceivable", 'received' => "$allReceived"]
            ];
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            if ($return) {
                throw new \Exception($e->getMessage());
            }
            return $this->sendErrorResponse($e->getCode() ?: 500, '系统异常', $e->getMessage());
        }
    }


    /**
     * 展示应缴及流水记录
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180915
     */
    public function detailAndFlowAction()
    {
        $userId = $this->request->getQuery('userId', 'int');
        $year   = $this->request->getQuery('year', 'int');
        if (!$userId) {
            return $this->sendViewError('缺少用户id');
        }
        if (!$year) {
            return $this->sendViewError('无年份或该年份下无记录');
        }
        $this->view->pick('cost/detailAndFlow');
        try {
            $params = [
                'conditions' => 'bDelete = 0 AND year = :year: AND userId = :userId:',
                'bind' => ['year' => $year, 'userId' => $userId],
                'order' => 'id desc'
            ];
            $details = CostChargeDetail::find($params)->toArray();
            $flows = CostChargeFlow::find($params)->toArray();
            Tool::runTimestamp($details, ['serviceStart', 'serviceEnd'], true, 'Y-m-d');
            Tool::runTimestamp($flows, ['receiveTime']);
            Tool::runEnum($flows, Charge::$enum);
            return $this->view->setVars([
                'details' => $details,
                'flows' => $flows,
                'power' => [
                    'detail' => Power::exist('chargeDetail_Del'),
                    'flow' => Power::exist('chargeFlow_Del')
                ]
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 收费总表导出
     *
     * @return bool|string
     *
     * create by ck 20180929
     */
    public function exportChargeAction()
    {
        $this->view->disable();
        $title = Template::getXmlFields('Cost_Charge');
        $data  = $this->getChargeAction(true);
        if (!$data) {
            return $this->sendViewError('无数据可导出');
        }
        $keys = array_keys($title);
        foreach ($data as &$row) {
            $temp = [];
            foreach ($keys as $key) {
                $temp[$key] = $row[$key];
            }
            $row = $temp;
        }
        Tool::exportExcelOnline('收费总表', array_values($title), $data);
        return true;
    }

    /**
     * 修改学校编号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181026
     */
    public function changeSchoolCodeAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $code = $this->request->getPost('code', 'string');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少学校id');
        }
        if (!$code) {
            return $this->sendErrorResponse(400, '编号不能为空');
        }
        if (!Power::exist('chargeTotal_Code')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        try {
            School::setSchoolCode($schoolId, $code);
            return $this->sendSuccessResponse('编号修改成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 应缴列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180917
     */
    public function chargeDetailAction()
    {
        $this->view->pick('cost/chargeDetail');
        Main::showNavPosition();
        Assets::easyUI('js/cost/chargeDetail.js');
        if (!Power::exist('chargeDetail')) {
            return $this->sendViewError('无查看此页面权限');
        }

        $schSearchArr = $listButtonArr = $listSearchArr = [];
        $schSearchArr[] = ['type'=>'select', 'id'=>'list_school_status', 'multiple' => 'true',
            'data' => School::$enum['iStatus'], 'style' => 'width: 100px'];
        $schSearchArr[] = ['type' => 'text', 'id' => 'list_school_vague', 'label' => ' 搜索：'];
        $schSearchArr[] = ['type' => 'button', 'id' => 'bt_list_school_search', 'text' => ' 查找', 'icon' => 'fa-search'];

        $listSearchArr[] = ['type' => 'select', 'id' => 'list_year', 'style' => 'width:60px;',
            'data' => $this->getYearEnum(), 'default' => date('Y')];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague', 'label' => ' 姓名/账号：'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_className', 'label' => ' 班级：',
            'style' => 'width:100px !important;'];
        $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_startTime',
            'label' => ' 导入时间: ', 'style' => 'width:100px !important;'];
        $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_endTime',
            'label' => '~', 'style' => 'width:100px !important;'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_export', 'text' => '导出',
            'icon' => 'fa-file-excel-o', 'style' => 'margin-left:10px'];

        if (Power::exist('chargeDetail_Add')) {
            $listButtonArr[] = ['id' => 'bt_list_import', 'text' => '应缴导入', 'icon' => 'fa-file-excel-o'];
        }
        if (Power::exist('chargeDetail_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_splitAll', 'text' => '一键拆分', 'icon' => 'fa-clone'];
        }
        if (Power::exist('chargeDetail_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        return $this->view->setVars([
            'SchoolList' => Template::createList('schoolList', 'Cost_School', [
                'checkbox' => false,
                'searchToolbar' => Template::createSearchToolBar($schSearchArr)
            ]),
            'List' => Template::createList('list', 'Cost_ChargeDetail', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取应缴列表
     *
     * @param bool $return
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by ck 20180917
     * modify by ck 20180918
     */
    public function getChargeDetailAction($return = false)
    {
        $year     = $this->request->get('year', 'string');
        $schoolId = $this->request->get('schoolId', 'int');
        $startTime= $this->request->get('startTime', 'string');
        $endTime  = $this->request->get('endTime', 'string');
        $vague    = $this->request->get('vague', 'string');
        $className= $this->request->get('className', 'string');
        try {
            if (!Power::exist('chargeDetail')) {
                throw new \Exception('无权限', 403);
            }
            if (!$schoolId) {
                throw new \Exception('缺少学校id', 400);
            }
            if (!$year) {
                throw new \Exception('缺少年份信息', 400);
            }
            if (!School::hasPower($schoolId)) {
                throw new \Exception('无该学校权限', 403);
            }

            $conditions = '';
            if ($startTime) {
                $conditions .= " AND d.tCreateDate >= '{$startTime}'";
            }
            if ($endTime) {
                $endTime = Tool::getEndTime($endTime, false);
                $conditions .= " AND d.tCreateDate < '{$endTime}'";
            }
            if ($vague) {
                $conditions .= Main::runVagueCondition(['u.sUserName', 'u.sLogonName'], $vague);
            }
            if ($className) {
                $conditions .= Main::runVagueCondition(['u.sAdClsName'], $className);
            }

            $sql = "SELECT 
                        u.iUserId,u.sUserName,u.sLogonName,u.sAdClsName,
                        d.id,d.year,d.receivable,d.serviceStart,d.serviceEnd,
                        d.devPrice,d.depositPrice,d.servicePrice,d.tutorPrice,d.tCreateDate,d.iCreateUserId
                    FROM XHCost_ChargeDetail AS d
                    LEFT JOIN XHSys_User AS u ON u.iUserId = d.userId 
                    WHERE d.bDelete = 0 AND d.year = '{$year}'
                      AND u.bDelete = 0 AND u.iUserType = 1 AND u.iSchoolId = {$schoolId}
                      {$conditions}
                    ORDER BY id DESC";
            $data = Main::runSqlPage($sql);
            Tool::runTimestamp($data['rows'], ['serviceStart', 'serviceEnd'], true, 'Y-m-d');
            Main::runUserName($data['rows'], ['iCreateUserId' => 'sCreateUserName']);
            if ($return) {
                return $data['rows'];
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            if ($return) {
                throw new \Exception($e->getMessage());
            }
            return $this->sendErrorResponse($e->getCode() ?: 500, $e->getMessage());
        }
    }

    /**
     * 删除应缴记录
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180918
     */
    public function delChargeDetailAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, 'id不能为空');
        }
        if (!Power::exist('chargeDetail_Del')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        try {
            Charge::delDetail($ids);
            return $this->sendSuccessResponse('删除成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 批量拆分(根据学校，年份，应缴)
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181017
     */
    public function splitChargeBatchAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $receivable = $this->request->getPost('receivable');
        $year = $this->request->getPost('year', 'int');
        $devPrice = $this->request->getPost('devPrice', null, 0);
        $depositPrice = $this->request->getPost('depositPrice', null, 0);
        $servicePrice = $this->request->getPost('servicePrice', null, 0);
        $tutorPrice = $this->request->getPost('tutorPrice', null, 0);
        $userIds = $this->request->getPost('userIds');

        if (!Power::exist('chargeDetail_Edit')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
//        if (!School::hasPower($schoolId, true)) {
//            return $this->sendErrorResponse(403, '无该学校管理权限');
//        }
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '学校id不能为空');
        }
        if (!$receivable || !$year) {
            return $this->sendErrorResponse(400, '应缴或年份不能为空');
        }
        if (($devPrice + $depositPrice + $servicePrice + $tutorPrice) != $receivable) {
            return $this->sendErrorResponse(400, '拆分金额需与应缴相等');
        }
        try {
            if (empty($userIds)) {// 不指定id拆分
                $sql = "SELECT c.id 
                  FROM XHCost_ChargeDetail AS c
                  RIGHT JOIN XHSys_User AS u ON c.userId = u.iUserId 
                  WHERE u.bDelete = 0 AND u.bDisable = 0 AND u.bHistory = 0 AND c.bDelete = 0
                    AND u.iSchoolId = '{$schoolId}' AND c.receivable = '{$receivable}' AND c.`year` = '{$year}'";
                //获取符合记录id
            } else {
                $userIds = '('.implode(',', $userIds).')';
                $sql = "SELECT c.id 
                  FROM XHCost_ChargeDetail AS c
                  RIGHT JOIN XHSys_User AS u ON c.userId = u.iUserId 
                  WHERE u.bDelete = 0 AND u.bDisable = 0 AND u.bHistory = 0 AND c.bDelete = 0
                    AND u.iSchoolId = '{$schoolId}' AND c.receivable = '{$receivable}' AND c.`year` = '{$year}' AND 
                    c.userId in $userIds";
            }
            $ids = $this->db->fetchAll($sql);
            $ids = array_column($ids, 'id');
            if (!$ids) {
                return $this->sendErrorResponse(400, '该条件下无对应记录');
            }
            $idStr = implode(',', $ids);
            $result = $this->db->update(
                'XHCost_ChargeDetail',
                ['devPrice', 'depositPrice', 'servicePrice', 'tutorPrice', 'iLastModifyUserId', 'tLastModifyDate'],
                [$devPrice, $depositPrice, $servicePrice, $tutorPrice, User::getId(), date('Y-m-d H:i:s')],
                "id IN ({$idStr})"
            );
            if (!$result) {
                throw new XhException('拆分失败');
            }
            return $this->sendSuccessResponse(sprintf('成功拆分%d条', count($ids)));
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 流水列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180917
     */
    public function chargeFlowAction()
    {
        $this->view->pick('cost/chargeFlow');
        Main::showNavPosition();
        Assets::easyUI('js/cost/chargeFlow.js');
        if (!Power::exist('chargeFlow')) {
            return $this->sendViewError('无查看此页面权限');
        }

        $schSearchArr = $listButtonArr = $listSearchArr = [];
        $schSearchArr[] = ['type'=>'select', 'id'=>'list_school_status', 'multiple' => 'true',
            'data' => School::$enum['iStatus'], 'style' => 'width: 100px'];
        $schSearchArr[] = ['type' => 'text', 'id' => 'list_school_vague', 'label' => ' 搜索：'];
        $schSearchArr[] = ['type' => 'button', 'id' => 'bt_list_school_search', 'text' => ' 查找',
            'icon' => 'fa-search'];

        $listSearchArr[] = ['type' => 'select', 'id' => 'list_year', 'style' => 'width:60px;',
            'data' => $this->getYearEnum(), 'default' => date('Y')];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague', 'label' => ' 姓名/账号：'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_className', 'label' => ' 班级：',
            'style' => 'width:100px !important;'];
        $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_startTime',
            'label' => ' 导入时间: ', 'style' => 'width:100px !important;'];
        $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_endTime',
            'label' => '~', 'style' => 'width:100px !important;'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_export', 'text' => '导出',
            'icon' => 'fa-file-excel-o', 'style' => 'margin-left:10px'];

        if (Power::exist('chargeFlow_NoImport')) {
            $listButtonArr[] = ['id' => 'bt_list_import', 'text' => '账号导入', 'icon' => 'fa-file-excel-o'];
        }
        if (Power::exist('chargeFlow_NameImport')) {
            $listButtonArr[] = ['id' => 'bt_list_importName', 'text' => '姓名导入', 'icon' => 'fa-file-excel-o'];
        }
        if (Power::exist('chargeFlow_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        return $this->view->setVars([
            'SchoolList' => Template::createList('schoolList', 'Cost_School', [
                'checkbox' => false,
                'searchToolbar' => Template::createSearchToolBar($schSearchArr)
            ]),
            'List' => Template::createList('list', 'Cost_ChargeFlow', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取实缴列表
     *
     * @param bool $return
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by ck 20180917
     * modify by ck 20181026    学校权限判断
     */
    public function getChargeFlowAction($return = false)
    {
        $year     = $this->request->get('year', 'string');
        $schoolId = $this->request->get('schoolId', 'int');
        $startTime= $this->request->get('startTime', 'string');
        $endTime  = $this->request->get('endTime', 'string');
        $vague    = $this->request->get('vague', 'string');
        $className= $this->request->get('className', 'string');
        try {
//            if (!$schoolId) {
//                throw new \Exception('缺少学校id');
//            }
            if (!$year) {
                throw new \Exception('缺少年份信息', 400);
            }

            $conditions = '';
            if ($startTime) {
                $conditions .= " AND f.tCreateDate >= '{$startTime}'";
            }
            if ($endTime) {
                $endTime = Tool::getEndTime($endTime, false);
                $conditions .= " AND f.tCreateDate < '{$endTime}'";
            }
            if ($vague) {
                $conditions .= Main::runVagueCondition(['u.sUserName', 'u.sLogonName'], $vague);
            }
            if ($className) {
                $conditions .= Main::runVagueCondition(['u.sAdClsName'], $className);
            }
            if ($schoolId) {
                if (!School::hasPower($schoolId)) {
                    throw new \Exception('无该学校权限', 403);
                }
                $conditions .= " AND u.iSchoolId = {$schoolId} ";
            } else {
                $schoolPower = School::getPower();
                if (!$schoolPower) {
                    throw new \Exception('无学校权限', 403);
                } elseif ($schoolPower !== true) {
                    $schoolPowerIds = implode(',', $schoolPower);
                    $conditions .= " AND u.iSchoolId IN ({$schoolPowerIds}) ";
                }
            }
            $sql = "SELECT 
                        u.iUserId,u.sUserName,u.sLogonName,u.sAdClsName,
                        f.id,f.year,f.receiveNum,f.receiveTime,f.sourceType,
                        f.sourceName,f.sourceNo,f.remark,f.tCreateDate,f.iCreateUserId
                    FROM XHCost_ChargeFlow AS f
                    LEFT JOIN XHSys_User AS u ON u.iUserId = f.userId 
                    WHERE f.bDelete = 0 AND f.year = '{$year}'
                      AND u.bDelete = 0 AND u.iUserType = 1
                      {$conditions}
                    ORDER BY id DESC";

            $data = Main::runSqlPage($sql, Charge::$enum);
            Tool::runTimestamp($data['rows'], ['serviceStart', 'serviceEnd'], true, 'Y-m-d');
            Tool::runTimestamp($data['rows'], ['receiveTime']);
            Main::runUserName($data['rows'], ['iCreateUserId' => 'sCreateUserName']);
            if ($return) {
                return $data['rows'];
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            if (!$return) {
                throw new \Exception($e->getMessage());
            }
            return $this->sendErrorResponse($e->getCode() ?: 500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 删除流水
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180918
     */
    public function delChargeFlowAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, 'id不能为空');
        }
        if (!Power::exist('chargeFlow_Del')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        try {
            Charge::delFlow($ids);
            return $this->sendSuccessResponse('删除成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 导入缴费记录（初始化）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180913
     */
    public function importChargeDetailAction()
    {
        $year         = $this->request->getPost('year', 'int');
        $schoolId     = $this->request->getPost('schoolId', 'int');
        $autoClass    = $this->request->getPost('autoClass', 'int');
        $serviceStart = $this->request->getPost('serviceStart', 'string');
        $serviceEnd   = $this->request->getPost('serviceEnd', 'string');
        $file         = $this->request->getUploadedFiles()[0];
        if (!$year || !$file) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        if (!School::isApproval($schoolId)) {
            return $this->sendErrorResponse(400, '该学校未审核，无法导入');
        }
        if (!$serviceStart) {
            $serviceStart = 0;
        } else {
            $serviceStart = strtotime($serviceStart);
        }
        if (!$serviceEnd) {
            $serviceEnd = 0;
        } else {
            $serviceEnd = strtotime($serviceEnd . '+1 day') - 1;
        }

        //读取数据并写入数据库
        try {
            $this->db->begin();
            $importNum  = $totalNum = 0;
            $errorUser  = $newUser  = $classInfo = [];
            $result     = Tool::readExcel($file->getTempName(), true, $file->getExtension());
            $titleArr   = $result['title'];
            $rows       = $result['data'];

            //检查必要参数是否存在，并替换其index值
            $mainIndex = ['name' => '姓名', 'code' => '缴费编号', 'receivable' => '应缴总额', 'class' => '班级'];
            foreach ($mainIndex as $key => $name) {
                $index = array_search($name, $titleArr);
                if ($index === false) {
                    return $this->sendErrorResponse(400, "缺少[{$name}]项信息");
                }
                $mainIndex[$key] = $index;
            }

            //判断学校名称
//            foreach ($rows as $row) {
//                if ($row[$mainIndex['school']] && $row[$mainIndex['school']] != $schoolName) {
//                    return $this->sendErrorResponse(400, '学校名称有误或不统一', $row);
//                }
//                if ($row[$mainIndex['class']]) {
//                    if (!is_numeric($row[$mainIndex['class']]) || strlen($row[$mainIndex['class']]) !== 4) {
//                        return $this->sendErrorResponse(400, '班级名称不正确，请确认', $row);
//                    }
//                }
//            }

            //检查额外参数是否存在，存在则替换index，过滤并写入数据库
            $extraIndex = [
//                'received'      => '实缴总额',
                'iUserSex'      => '性别',
                'sIdentityCode' => '证件号',
                'sMotherName'   => '母亲姓名',
                'sMotherPhone'  => '母亲电话',
                'sFatherName'   => '父亲姓名',
                'sFatherPhone'  => '父亲电话',
                'sOtherName'    => '监护人姓名',
                'sOtherPhone'   => '监护人电话',
                'pClass'        => '培优班'
            ];
            foreach ($extraIndex as $key => $name) {
                $extraIndex[$key] = array_search($name, $titleArr);
            }
            $extraIndex = array_filter($extraIndex);

            foreach ($rows as $row) {
                //缺少参数则跳过
                if (!$row[$mainIndex['code']]) {
                    continue;
                }

                $totalNum++;
                //检查用户是否存在或多个
                try {
                    $row[$mainIndex['code']] = trim($row[$mainIndex['code']]);
                    $userId = $this->getStudIdByCode($row[$mainIndex['code']], $schoolId);
                } catch (\Exception $e) {
                    //新建账号
                    if ($e->getCode() == 404) {
                        try {
                            $this->db->begin();

                            //处理用户表
                            $user = new XhsysUser();
                            $user->sLogonName   = $row[$mainIndex['code']];
                            $user->sUserName    = $row[$mainIndex['name']];
                            $user->sAdClsName   = $row[$mainIndex['class']];
                            $user->sLogonPwd    = strtoupper(md5('123456'));
                            $user->iSchoolId    = $schoolId;
                            $user->iUserType    = 1;
                            if (isset($extraIndex['iUserSex'])) {
                                $user->iUserSex = XhsysUser::getSexCode($row[$extraIndex['iUserSex']]);
                            }
                            foreach (['sMotherPhone', 'sFatherPhone', 'sOtherPhone', 'sIdentityCode'] as $key) {
                                if (isset($extraIndex[$key])) {
                                    $user->$key = $row[$extraIndex[$key]];
                                }
                            }
                            if (!$user->insertAfterOld(true)) {
                                throw new \Exception($user->getError());
                            }
                            $userId = $user->iUserId;

                            //处理学生表
                            $stud = new XhsysUserstud();
                            $stud->iUserId = $userId;
                            foreach (['sMotherName', 'sFatherName', 'sOtherName'] as $key) {
                                if (isset($extraIndex[$key])) {
                                    $stud->$key = $row[$extraIndex[$key]];
                                }
                            }
                            $stud->save();


                            //处理新增班级信息
                            switch ($autoClass) {
                                case 1:
                                    if ($row[$mainIndex['class']]) {
                                        $classInfo[$row[$mainIndex['class']]][] = $userId;
                                    }
                                    break;
                                case 2:
                                    if (isset($extraIndex['pClass']) && $row[$extraIndex['pClass']]) {
                                        $classInfo[$row[$extraIndex['pClass']]][] = $userId;
                                    }
                                    break;
                            }

                            $newUser[] = ['id' => $userId, 'name' => $user->sUserName , 'code' => $user->sLogonName];
                            $this->db->commit();
                        } catch (\Exception $e) {
                            $this->db->rollback();
                            $errorUser[] = [
                                'name' => $row[$mainIndex['name']],
                                'code' => $row[$mainIndex['code']],
                                'reason' => '创建失败：' . $e->getMessage()
                            ];
                            continue;
                        }
                    } else {
                        $errorUser[] = [
                            'name' => $row[$mainIndex['name']],
                            'code' => $row[$mainIndex['code']],
                            'reason' => $e->getMessage(),
                            'receivable' => floatval($row[$mainIndex['receivable']]),
                            'serviceStart' => $serviceStart,
                            'serviceEnd' => $serviceEnd,
                            'class' => $row[$mainIndex['class']]
                        ];
                        continue;
                    }
                }

                //写入缴费数据
                try {
                    Charge::importDetail($year, $userId, floatval($row[$mainIndex['receivable']]), [
//                        'received' => $row[$extraIndex['received']] ?? 0,
                        'serviceStart' => $serviceStart,
                        'serviceEnd' => $serviceEnd,
                    ]);
                } catch (XhException $e) {
                    $errorUser[] = [
                        'name' => $row[$mainIndex['name']],
                        'code' => $row[$mainIndex['code']],
                        'reason' => '保存失败：' . $e->getMessage()
                    ];
                    continue;
                }
                $importNum++;
            }
            $this->db->commit();
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        $msg = "成功导入{$importNum}条！（共{$totalNum}条）";
        if ($newUser) {
            $msg .= '。创建新账号：' . count($newUser) . '个';
            if ($classInfo) {
                try {
                    UserService::initStudClass($schoolId, $classInfo, $autoClass - 1);
                } catch (\Exception $e) {
                }
            }
        }
        return $this->sendJsonResponse([
            'msg'       => $msg,
            'errorData' => $errorUser,
            'newUser'   => $newUser
        ], true);
    }

    /**
     * 导入缴费流水
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180914
     * modify by ck 20181022    判断流水号
     */
    public function importChargeFlowAction()
    {
        $type     = $this->request->getPost('type', 'int');
        $year     = $this->request->getPost('year', 'int');
        $schoolId = $this->request->getPost('schoolId', 'int');
        $file     = $this->request->getUploadedFiles()[0];
        if (!$type || !$year || !$file) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }

        //读取数据并写入数据库
        try {
            $this->db->begin();
            $importNum  = $totalNum = 0;
            $errorUser  = [];
            $result     = Tool::readExcel($file->getTempName(), true, $file->getExtension());
            $titleArr   = $result['title'];
            $rows       = $result['data'];

            //检查必要参数是否存在，并替换其index值
            switch ($type) {
                case 1:
                    $mainIndex = ['name' => '姓名', 'code' => '缴费编号', 'received' => '发生金额', 'time' => '交易时间'];
                    break;
                case 2:
                    $mainIndex = ['name' => '姓名', 'received' => '发生金额', 'time' => '交易时间'];
                    break;
                default:
                    return $this->sendErrorResponse(400, '导入类型不正确');
            }
            foreach ($mainIndex as $key => $name) {
                $index = array_search($name, $titleArr);
                if ($index === false) {
                    return $this->sendErrorResponse(400, "缺少[{$name}]项信息");
                }
                $mainIndex[$key] = $index;
            }

            $extraIndex = [
                'class'    => '班级',
                'bankName' => '银行名称',
                'bankNo'   => '银行流水号',
                'remark'   => '备注'
            ];
            foreach ($extraIndex as $key => $name) {
                $extraIndex[$key] = array_search($name, $titleArr);
            }
            $extraIndex = array_filter($extraIndex);

            foreach ($rows as $row) {
                //缺少参数则跳过
                if (!$row[$mainIndex[$type == 1 ? 'code' : 'name']]) {
                    continue;
                }

                $totalNum++;
                //检查用户是否存在或多个
                try {
                    $row[$mainIndex['code']] = trim($row[$mainIndex['code']]);
                    $userId = $type ==1
                        ? $this->getStudIdByCode($row[$mainIndex['code']])
                        : $this->getStudIdByName($row[$mainIndex['name']], $schoolId);
                } catch (\Exception $e) {
                    $errorUser[] = [
                        'name' => $row[$mainIndex['name']],
                        'code' => $row[$mainIndex['code']] ?? '',
                        'reason' => $e->getMessage()
                    ];
                    continue;
                }

                //写入缴费数据
                try {
                    Charge::importFlow(
                        $year,
                        $userId,
                        floatval($row[$mainIndex['received']]),
                        strtotime($row[$mainIndex['time']]),
                        $type,
                        [
                            'sourceName' => $row[$extraIndex['bankName']] ?? '',
                            'sourceNo' => $row[$extraIndex['bankNo']] ?? '',
                            'remark' => $row[$extraIndex['remark']] ?? '',
                        ]
                    );
                } catch (XhException $e) {
                    $errorUser[] = [
                        'name' => $row[$mainIndex['name']],
                        'code' => $row[$mainIndex['code']],
                        'reason' => '保存失败：' . $e->getMessage()
                    ];
                    continue;
                }
                $importNum++;
            }
            $this->db->commit();
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        $msg = "成功导入{$importNum}条！（共{$totalNum}条）";
        return $this->sendJsonResponse([
            'msg'       => $msg,
            'errorData' => $errorUser,
        ], true);
    }

    /**
     * 导出应缴列表
     *
     * @return bool|string
     *
     * create by ck 20181029
     */
    public function exportChargeDetailAction()
    {
        try {
            $title = Template::getXmlFields('Cost_ChargeDetail');
            $data  = $this->getChargeDetailAction(true);
            if (!$data) {
                return $this->sendViewError('无数据可导出');
            }
            $keys = array_keys($title);
            foreach ($data as &$row) {
                $temp = [];
                foreach ($keys as $key) {
                    $temp[$key] = $row[$key] ?? '';
                }
                $row = $temp;
            }
            $this->view->disable();
            Tool::exportExcelOnline('应缴列表', array_values($title), $data);
            return true;
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 导出流水列表
     *
     * @return bool|string
     *
     * create by ck 20181029
     */
    public function exportChargeFlowAction()
    {
        try {
            $title = Template::getXmlFields('Cost_ChargeFlow');
            $data  = $this->getChargeFlowAction(true);
            if (!$data) {
                return $this->sendViewError('无数据可导出');
            }
            $keys = array_keys($title);
            foreach ($data as &$row) {
                $temp = [];
                foreach ($keys as $key) {
                    $temp[$key] = $row[$key] ?? '';
                }
                $row = $temp;
            }
            $this->view->disable();
            Tool::exportExcelOnline('实缴列表', array_values($title), $data);
            return true;
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }


    private $studChargeEnum = [
        'bImport'       => [0 => '手动', 1 => '账号导入', 2 => '姓名导入'],
        'iState'        => [0 => '未审核', 1 => '审核通过', 2 => '申请修改', 3 => '待修改', 4 => '无需审核'],
        'bSplitLock'    => [0 => '未锁定', 1 => '已锁定'],
//        'bEbook'        => [0 => '', 1 => '<i class="fa fa-check"></i>'],
        'bEbook'        => [0 => '', 1 => '√'],
    ];

    /**
     * 学生收费页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20170715
     * modify by ck 20170902    增加学生筛选
     */
    public function studChargeAction()
    {
        return $this->sendViewError('该功能维护中...');
        $this->view->pick('cost/studCharge');
        Main::showNavPosition();
        Assets::easyUI('js/cost/studCharge.js');
        Assets::datetimePicker();
        if (!Power::exist('Cost_StudCharge')) {
            return $this->sendViewError('无查看此页面权限');
        }

        //学校搜索条件
        $schSearchArr = $studButtonArr = $studSearchArr = [];
        $schSearchArr[] = ['type' => 'text', 'id' => 'list_school_vague', 'label' => '搜索：'];
        $schSearchArr[] = ['type' => 'button', 'id' => 'bt_list_school_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];

        //处理缴费年度条件
        $nowYear = date('Y');
        $yearArr = ['' => '-年份-'];
//        $yearArr = [];
        for ($year = $nowYear - 2; $year <= $nowYear + 1; $year++) {
            $yearArr[$year] = $year;
        }

        //学生搜索条件
        $studSearchArr[] = ['type' => 'select', 'id' => 'list_stud_history', 'style' => 'width: 50px;', 'data' => [0 => '正常', 1 => '历史']];
        $studSearchArr[] = ['type' => 'select', 'id' => 'list_stud_year', 'style' => 'width:60px;', 'data' => $yearArr, 'default' => $nowYear];
        $studSearchArr[] = ['type' => 'select', 'id' => 'list_stud_charge', 'style' => 'width:60px;', /*'label' => ' 状态：',*/
            'data' => ['' => '全部', 0 => '未缴费', 1 => '已缴费']];
        $studSearchArr[] = ['type' => 'select', 'id' => 'list_stud_cost_target', 'multiple' => 'true', 'style' => 'width:60px;', 'label' => ' 应缴：', 'data' => [
            '' => '-类型-',
            'iSerCost' => '服务费',
            'iDevCost' => '设备费',
            'iDeposit' => '押金 ',
            'iRentCost' => '租金'
        ]];
        $studSearchArr[] = ['type' => 'text', 'id' => 'list_stud_vague', 'label' => ' 姓名/账号：'];
        $studSearchArr[] = ['type' => 'text', 'id' => 'list_stud_class', 'label' => ' 班级：', 'style' => 'width:100px !important;'];
        $studSearchArr[] = ['type' => 'select', 'id' => 'list_time_type', 'style' => 'width:80px;', 'label' => ' ', 'data' => [
            1 => '缴费时间',
            2 => '创建时间',
        ]];
        $studSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_startTime', /*'label' => ' 缴费时间：',*/
            'style' => 'width:100px !important;'];
        $studSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_endTime', 'label' => '~', 'style' => 'width:100px !important;'];
        $studSearchArr[] = ['type' => 'button', 'id' => 'bt_list_stud_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $studSearchArr[] = ['type' => 'button', 'id' => 'bt_list_stud_export', 'text' => '导出', 'icon' => 'fa-file-excel-o', 'style' => 'margin-left:10px'];
        if (Power::exist('Cost_StudCharge_Add')) {
            $studButtonArr[] = ['id' => 'bt_list_stud_add', 'text' => '缴费', 'icon' => 'fa-plus'];
        }
        if (Power::exist('Cost_StudCharge_Import')) {
            $studButtonArr[] = ['id' => 'bt_list_stud_import', 'text' => '账号导入', 'icon' => 'fa-file-excel-o'];
        }
        if (Power::exist('Cost_StudCharge_JournalImport')) {
            $studButtonArr[] = ['id' => 'bt_list_stud_journal_import', 'text' => '流水导入', 'icon' => 'fa-file-excel-o'];
        }
        if (Power::exist('Cost_StudCharge_HandImport')) {
            $studButtonArr[] = ['id' => 'bt_list_stud_hand_import', 'text' => '姓名导入', 'icon' => 'fa-file-excel-o'];
        }
        if (Power::exist('Cost_StudCharge_Edit')) {
            $studButtonArr[] = ['id' => 'bt_list_stud_split', 'text' => '拆分', 'icon' => 'fa-clone'];
            $studButtonArr[] = ['id' => 'bt_list_stud_split_all', 'text' => '一键拆分', 'icon' => 'fa-clone'];
            $studButtonArr[] = ['id' => 'bt_list_stud_split_unlock', 'text' => '解锁拆分', 'icon' => 'fa-unlock'];
        }
        if (Power::exist('Cost_StudCharge_Audit')) {
            $studButtonArr[] = ['id' => 'bt_list_stud_audit', 'text' => '审核通过', 'icon' => 'fa-legal'];
            $studButtonArr[] = ['id' => 'bt_list_stud_pass', 'text' => '可修改', 'icon' => 'fa-history'];
        } else {
            $studButtonArr[] = ['id' => 'bt_list_stud_apply', 'text' => '申请修改', 'icon' => 'fa-edit'];
        }
        if (Power::exist('Cost_StudCharge_Del')) {
            $studButtonArr[] = ['id' => 'bt_list_stud_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        return $this->view->setVars([
            'SchoolList' => Template::createList('SchoolList', 'Cost_School', array(
                'checkbox' => false,
                'searchToolbar' => Template::createSearchToolBar($schSearchArr)
            )),
            'StudList' => Template::createList('StudList', 'Cost_StudCharge', [
                'searchToolbar' => Template::createSearchToolBar($studSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($studButtonArr)
            ]),
        ]);
    }

    /**
     * 根据学校获取学生及收费信息
     *
     * @param bool $return
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|array
     *
     * create by ck 20170715
     * modify by ck 20170831    添加页脚统计数据
     * modify by ck 20170902    增加学生筛选
     * modify by ck 20171114    增加筛选条件
     * modify by ck 20180123    更改筛选，多条数据则显示总计
     * modify by ck 20180226    添加班级/姓名/身份证排序
     * modify by ck 20180621
     */
    public function getStudChargeAction($return = false)
    {
        return $this->sendErrorResponse(403, '该功能维护中...');
        $schoolId   = $this->request->get('schoolId', 'int');
        $chargeYear = $this->request->get('chargeYear', 'int');
        $isCharge   = $this->request->get('isCharge', 'int');
        $sort       = $this->request->get('sort', 'string');
        $order      = $this->request->get('order', 'string');
        $costTarget = $this->request->get('costTarget', 'string');
        $className  = $this->request->get('className', 'string');
        $timeType   = $this->request->get('timeType', 'int');
        $startTime  = $this->request->get('startTime', 'string');
        $endTime    = $this->request->get('endTime', 'string');
        $history    = $this->request->get('history', 'int', 0);
        $costTarget = $costTarget ? array_filter($costTarget) : [];
        if (!$schoolId) {
//            return $this->sendErrorResponse(400, '学校id不能为空！');
            return $return ? $this->sendViewError('学校id不能为空') : $this->sendDataGridError('缺少学校id');
        }
        try {
            //处理筛选条件
            $conditionOn = '';
//            $conditions  = "( U.iUserType = 1 AND U.bDelete = 0 AND U.bDisable = 0 AND U.bCompany = 0 AND U.bHistory = 0 ) AND (U.iSchoolId = '{$schoolId}')";
            $conditions  = "( U.iUserType = 1 AND U.bDelete = 0 AND U.bDisable = 0 AND U.bHistory = {$history} ) AND (U.iSchoolId = '{$schoolId}')";

            if ($chargeYear) {
                $conditionOn .= " AND C.iChargeYear = '{$chargeYear}'";
            }
            if ($timeType == 1) {
                if ($startTime) {
                    $conditionOn .= " AND C.tChargeTime >= '{$startTime}'";
                }
                if ($endTime) {
                    $endTime = date('Y-m-d', strtotime($endTime . ' +1 day'));
                    $conditionOn .= " AND C.tChargeTime <= '{$endTime}'";
                }
            } elseif ($timeType == 2) {
                if ($startTime) {
                    $conditions .= " AND U.tCreateDate >= '{$startTime}'";
                }
                if ($endTime) {
                    $endTime = date('Y-m-d', strtotime($endTime . ' +1 day'));
                    $conditions .= " AND U.tCreateDate <= '{$endTime}'";
                }
            }


            if ($isCharge !== null && $isCharge !== '') {
                $conditions .= $isCharge ? ' AND C.iSumCost > 0' : ' AND C.iSumDues > 0 AND (IFNULL(C.iSumCost, "") = "" OR C.iSumCost = 0)';
            }
            if ($costTarget) {
                $targetArr = ['iSerCost', 'iDevCost', 'iDeposit', 'iRentCost'];
                foreach ($targetArr as $target) {
                    if (in_array($target, $costTarget)) {
                        $conditions .= " AND C.{$target} > 0";
                    } else {
                        $conditions .= " AND C.{$target} = 0";
                    }
                }
            }
            if ($className) {
                $conditions .= Main::runVagueCondition(['U.sAdClsName'], $className);
//                if (strpos($className, ',') !== false) {
//                    $classNames = array_filter(explode(',', $className));
//                    $classNames = "'" . implode("','", $classNames) . "'";
//                    $conditions .= " AND U.sAdClsName IN ({$classNames})";
//                } else {
//                    $conditions .= " AND U.sAdClsName like '%{$className}%'";
//                }
            }
            Main::runSearchVagueConditions($conditions, ['U.sUserName', 'U.sLogonName']);
            $query = [
                'columns' => 'U.iUserId AS iUserId, U.sUserName AS sUserName, U.sLogonName AS sLogonName, U.sAdClsName AS sAdClsName, 
                    U.sIdentityCode AS sIdentityCode, U.bEbook AS bEbook, max(C.iCCId) AS iCCId, SUM(C.iSumDues) AS totalSumDues, 
                    C.iSumDues AS iSumDues, SUM(C.iSumCost) AS totalSumCost, C.iSumCost AS iSumCost, C.tChargeTime AS tChargeTime, 
                    C.tChargeImportTime AS tChargeImportTime, C.iChargeYear AS iChargeYear, SUM(C.iDevCost) AS totalDevCost, 
                    C.iDevCost AS iDevCost, SUM(C.iDeposit) AS totalDeposit, C.iDeposit AS iDeposit, SUM(C.iRentCost) AS totalRentCost, 
                    C.iRentCost AS iRentCost, SUM(C.iSerCost) AS totalSerCost, C.iSerCost AS iSerCost, C.iSerYear AS iSerYear, 
                    MAX(C.tStartTime) AS tStartTime,MAX(C.tExpireTime) AS tExpireTime, C.mRemarks AS mRemarks, C.bImport AS bImport, C.iState AS iState, C.bSplitLock AS bSplitLock,
                    U.sMotherPhone,U.sFatherPhone,U.sOtherPhone,S.sMotherName,S.sFatherName,S.sOtherName,U.tCreateDate',
                'query'   => "SELECT :columns: FROM XHSys_User AS U LEFT JOIN XHCost_StudCharge AS C ON U.iUserId = C.iStudId  AND IFNULL(C.bDelete, 0) = 0 {$conditionOn} 
                      LEFT JOIN XHSys_UserStud AS S ON U.iUserId = S.iUserId WHERE {$conditions} GROUP BY U.iUserId"
            ];
            if ($sort) {
                $query['query'] .= " ORDER BY U.{$sort} {$order}";
            }
            $data = Main::runSqlPage($query, $this->studChargeEnum);
            foreach ($data['rows'] as &$row) {
                if ($row['totalSumDues'] > $row['iSumDues']) {
                    $row['iSumDues'] = $row['totalSumDues'] . '/' . $row['iSumDues'];
                }
                if ($row['totalSumCost'] > $row['iSumCost']) {
                    $row['iSumCost'] = $row['totalSumCost'] . '/' . $row['iSumCost'];
                }
                if ($row['totalDevCost'] > $row['iDevCost']) {
                    $row['iDevCost'] = $row['totalDevCost'] . '/' . $row['iDevCost'];
                }
                if ($row['totalDeposit'] > $row['iDeposit']) {
                    $row['iDeposit'] = $row['totalDeposit'] . '/' . $row['iDeposit'];
                }
                if ($row['totalRentCost'] > $row['iRentCost']) {
                    $row['iRentCost'] = $row['totalRentCost'] . '/' . $row['iRentCost'];
                }
                if ($row['totalSerCost'] > $row['iSerCost']) {
                    $row['iSerCost'] = $row['totalSerCost'] . '/' . $row['iSerCost'];
                }
            }

            if ($return) {
                return $data['rows'];
            }

            //计算页脚
            $totalInfo = $this->db->fetchOne(str_replace(':columns:', 'SUM(iSumDues) AS iSumDues,SUM(iSumCost) AS iSumCost,SUM(C.iDevCost) AS iDevCost,SUM(iDeposit) AS iDeposit,COUNT(iSumCost) AS costNum', substr($query['query'], 0, strpos($query['query'], 'GROUP BY'))));
            $data['footer'][] = [
                'sUserName' => '总计',
                'iSumDues'  => $totalInfo['iSumDues'],
                'iSumCost'  => $totalInfo['iSumCost'],
                'iDevCost'  => $totalInfo['iDevCost'],
                'iDeposit'  => $totalInfo['iDeposit'],
                'iSerCost'  => $totalInfo['iSerCost'],
                'tChargeTime' => "人次：{$totalInfo['costNum']}/{$data['total']}"
            ];
//            $builder = $this->modelsManager->createBuilder()
//                ->columns(['U.iUserId', 'U.sUserName', 'U.sLogonName', 'U.sAdClsName', 'C.iCCId', 'C.iSumDues', 'C.iSumCost', 'C.tChargeTime', 'C.iChargeYear',
//                    'C.iDevCost', 'C.iDeposit', 'C.iRentCost', 'C.iSerCost', 'C.iSerYear', 'C.tExpireTime', 'C.mRemarks', 'C.bImport', 'C.iState', 'C.bSplitLock'])
//                ->from(['U' => '\\Admin\\Models\\user\\XhsysUser'])
//                ->leftJoin('\\Admin\\Models\\cost\\XhcostStudcharge', 'U.iUserId = C.iStudId AND IFNULL(C.bDelete, 0) = 0 AND IFNULL(C.bHistory, 0) = 0', 'C')
//                ->where('U.iUserType = 1 AND U.bDelete = 0 AND U.bDisable = 0 AND U.bCompany = 0 AND U.bHistory = 0')
//                ->andWhere('U.iSchoolId = :schoolId:', ['schoolId' => $schoolId]);
//            //处理筛选条件
//            if ($chargeYear) {
//                $builder->andWhere('C.iChargeYear = :chargeYear:', ['chargeYear' => $chargeYear]);
//            }
//            if ($isCharge !== null && $isCharge !== '') {
//                $builder->andWhere($isCharge ? 'C.iSumCost > 0' : 'C.iSumDues > 0 AND (IFNULL(C.iSumCost, "") = "" OR C.iSumCost = 0)');
//            }
//            if ($costTarget) {
//                $targetArr = ['iSerCost', 'iDevCost', 'iDeposit', 'iRentCost'];
//                foreach ($targetArr as $target) {
//                    if (in_array($target, $costTarget)) {
//                        $builder->andWhere("C.{$target} > 0");
//                    }
//                    else {
//                        $builder->andWhere("C.{$target} = 0");
//                    }
//                }
////                switch ($costTarget) {
////                    case 1: $builder->andWhere('C.iSerCost > 0 AND (C.iDevCost = 0 AND C.iDeposit = 0 AND C.iRentCost = 0)'); break;
////                    case 2: $builder->andWhere('C.iSerCost = 0 AND (C.iDevCost > 0 OR C.iDeposit > 0 OR C.iRentCost > 0)'); break;
////                    case 3: $builder->andWhere('C.iSerCost > 0 AND (C.iDevCost > 0 OR C.iDeposit > 0 OR C.iRentCost > 0)'); break;
////                }
//            }
//            $vagueCondition = '';
//            Main::runSearchVagueConditions($vagueCondition, ['U.sUserName']);
//            if ($vagueCondition) {
//                $builder->andWhere($vagueCondition);
//            }
//            $data = Main::runBuilderPage($builder, $this->chargeEnum);

            //计算页脚
//            $totalInfo = $builder->columns([
//                    'SUM(C.iSumDues) AS iSumDues',
//                    'SUM(C.iSumCost) AS iSumCost',
//                    'SUM(C.iDevCost) AS iDevCost',
//                    'SUM(C.iDeposit) AS iDeposit',
//                    'SUM(C.iSerCost) AS iSerCost',
//                ])
//                ->getQuery()
//                ->execute();
//            $totalInfo = $totalInfo->toArray()[0];
//            $costNum   = $builder->columns('COUNT(C.iSumCost) AS costNum')
//                ->andWhere('C.iSumCost > 0')
//                ->getQuery()
//                ->execute();
//            $costNum   = $costNum->toArray()[0]['costNum'];
//            $data['footer'][] = [
//                'sUserName' => '总计',
//                'iSumDues'  => $totalInfo['iSumDues'],
//                'iSumCost'  => $totalInfo['iSumCost'],
//                'iDevCost'  => $totalInfo['iDevCost'],
//                'iDeposit'  => $totalInfo['iDeposit'],
//                'iSerCost'  => $totalInfo['iSerCost'],
//                'tChargeTime' => "人次：{$costNum}/{$data['total']}"
//            ];
        }
        catch (\Exception $e) {
            return $return ? $this->sendViewError($e->getMessage()) : $this->sendErrorResponse(500, '获取失败', $e->getMessage());
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 缴费信息新增/修改/拆分
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20170823
     */
    public function studChargeModifyAction()
    {
        $type   = $this->request->getQuery('type', 'string');
        $id     = $this->request->getQuery('id', 'int');
        $ids    = $this->request->getQuery('ids', 'string');
        $studId = $this->request->getQuery('studId', 'int');
        $charge = null;
        if ($id) {
            $charge = XhcostStudcharge::findFirst($id);
        }
        switch ($type) {
            case 'create':
                if (!$studId) {
                    return $this->sendViewError('缺少学生id');
                }
                $powerTag = 'Cost_StudCharge_Add';
                break;
            case 'modify':
                if (!$id) {
                    return $this->sendViewError('缺少缴费id');
                }
                if (!$charge) {
                    return $this->sendViewError('找不到该缴费记录');
                }
                if ($charge->bImport != 0) {
                    return $this->sendViewError('导入数据无法修改');
                }
                if (!in_array($charge->iState, [0, 3]) && !Power::exist('Cost_StudCharge_Audit')) {
                    return $this->sendViewError('该记录暂不可修改');
                }
                $powerTag = 'Cost_StudCharge_Edit';
                break;
            case 'split':
                $ids = explode(',', $ids);
                if (!$ids) {
                    return $this->sendViewError('缺少缴费id');
                }
                $charges = XhcostStudcharge::find([
                    'columns'    => 'iCCId,iSumDues,iSumCost,bImport,bSplitLock',
                    'conditions' => 'iCCId IN ({idArr:array})',
                    'bind'       => ['idArr' => $ids]
                ])->toArray();
                if (!$charges) {
                    return $this->sendViewError('找不到记录');
                }
                $standard = $charges[0]['iSumDues'];
                foreach ($charges as $obj) {
                    if ($obj['iSumDues'] != $standard) {
                        return $this->sendViewError('应缴总额不相同，不可拆分');
                    }
                    if ($obj['iSumCost'] != $standard) {
                        return $this->sendViewError('含有未缴清记录，不可拆分');
                    }
                    if ($obj['bImport'] == 0) {
                        return $this->sendViewError('含有录入信息，不可拆分');
                    }
                    if ($obj['bSplitLock'] == 1) {
                        return $this->sendViewError('含有锁定记录，不可拆分');
                    }
                }
                $charge = [
                    'iSumDues' => $standard,
                    'iSumCost' => $standard,
                ];
                $powerTag = 'Cost_StudCharge_Edit';
//                if (!$id) {
//                    return $this->sendViewError('缺少缴费id');
//                }
//                if (!$charge) {
//                    return $this->sendViewError('找不到该缴费记录');
//                }
//                $powerTag = 'Cost_StudCharge_Edit';
//                if ($type == 'modify' && $charge->bImport == 1) {
//                    return $this->sendViewError('导入数据无法修改');
//                }
//                else if ($type == 'split' && $charge->bImport == 0){
//                    return $this->sendViewError('录入信息无法拆分');
//                }
//                if ($type == 'modify' && !in_array($charge->iState, [0, 3]) && !Power::exist('Cost_StudCharge_Audit')) {
//                    return $this->sendViewError('该记录暂不可修改');
//                }
                break;
            case 'splitAll':
                $powerTag = 'Cost_StudCharge_Edit';
                break;
            default: return $this->sendViewError('操作类型不正确');
        }
        if (!Power::exist($powerTag)) {
            return $this->sendViewError('无操作权限');
        }
        $this->view->pick('cost/studChargeModify');
        Assets::datetimePicker('js/cost/studChargeModify.js');
        return $this->view->setVars([
            'Form'       => Template::createForm('Cost_StudCharge'),
            'chargeInfo' => $charge
        ]);
    }

    /**
     * 新增/更改/拆分缴费信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by ck 20170824
     * modify by ck 20170922    添加租金
     * modify by ck 20170926    添加拆分锁定判断
     */
    public function modifyStudChargeAction()
    {
        $data = $this->request->getPost();
        $type = $data['type'];

        //检查权限
        switch ($type) {
            case 'create': $powerTag = 'Cost_StudCharge_Add'; break;
            case 'modify':
            case 'split':
            case 'splitAll': $powerTag = 'Cost_StudCharge_Edit'; break;
            default: return $this->sendErrorResponse(400, '操作类型错误');
        }
        if (!Power::exist($powerTag)) {
            return $this->sendErrorResponse(400, '无操作权限');
        }

        //分类操作
        if ($type == 'splitAll') {
            return $this->splitAllStudCharge($data);
        }
        else if ($type == 'split') {
            return $this->splitStudCharge($data);
        }
        else if ($type == 'create') {
            if (!$data['iStudId']){
                return $this->sendErrorResponse(400, '缺少学生id！');
            }
            if (!$data['iChargeYear'] || $data['iChargeYear'] > 2100 || $data['iChargeYear'] < 2000){
                return $this->sendErrorResponse(400, '缴费年度错误！');
            }
            if (!$data['iSumCost']){
                return $this->sendErrorResponse(400, '缴费总额有误！');
            }
            $oldCharge = XhcostStudcharge::findFirst([
                'conditions'    => 'bHistory = 0 AND bDelete = 0 AND iStudId = :studId:',
                'bind'          => ['studId' => $data['iStudId']]
            ]);
            if ($oldCharge) {
                if ($oldCharge->iChargeYear == $data['iChargeYear']) {
                    return $this->sendErrorResponse(400, '该缴费年度下已有记录');
                }
                $oldCharge->bHistory = 1;
                if (!$oldCharge->save()) {
                    return $this->sendErrorResponse(500, '历史数据操作失败');
                }
            }
            $charge = new XhcostStudcharge();
        }
        else {
            if (!$data['iCCId']){
                return $this->sendErrorResponse(400, '缺少缴费ID！');
            }
            $charge = XhcostStudcharge::findFirst($data['iCCId']);
            if (!$charge){
                return $this->sendErrorResponse(500, '找不到该记录！');
            }
            unset($data['iStudId'], $data['iCCId']);
//            if ($type == 'split') {
//                if ($charge->bImport != 1) {
//                    return $this->sendErrorResponse(400, '非导入数据无法拆分');
//                }
//                if ($charge->bSplitLock) {
//                    return $this->sendErrorResponse(400, '该记录已锁定，无法拆分');
//                }
//                $charge->bSplitLock = 1;
//                unset($data['iSumDues'], $data['iSumCost'], $data['iChargeYear'], $data['iChargeTime']);
//            }
//            else if ($type == 'modify') {
                if ($charge->bImport != 0) {
                    return $this->sendErrorResponse(400, '导入数据无法修改');
                }
                if (!in_array($charge->iState, [0, 3]) && !Power::exist('Cost_StudCharge_Audit')) {
                    return $this->sendErrorResponse(400, '该记录暂不可修改');
                }
//            }
        }
        $charge->assign($data);

        //有服务年限则计算到期时间
//        if ($charge->iSerYear) {
//            $charge->tExpireTime = date('Y-m-d H:i:s', strtotime($charge->tChargeTime . " + {$charge->iSerYear} year"));
//        }
        if (!$charge->save()) {
            return $this->sendErrorResponse(500, '保存失败');
        }
        return $this->sendSuccessResponse('保存成功');
    }

    /**
     * 一键拆分
     *
     * @param $data
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170831
     * modify by ck 20170922    添加租金
     * modify by ck 20171213    拆后锁定
     */
    private function splitAllStudCharge($data)
    {
        try {
            $chargeIdArr = $this->modelsManager->createBuilder()
                ->columns(['C.iCCId'])
                ->from(['U' => '\\Admin\\Models\\user\\XhsysUser'])
                ->leftJoin('\\Admin\\Models\\cost\\XhcostStudcharge', 'C.iStudId = U.iUserId ', 'C')
//                ->where('U.iUserType = 1 AND U.bDelete = 0 AND U.bDisable = 0 AND U.bCompany = 0 AND IFNULL(C.bDelete, 0) = 0 AND IFNULL(C.bHistory, 0) = 0 AND C.bImport <> 0 AND C.bSplitLock = 0')
                ->where('U.iUserType = 1 AND U.bDelete = 0 AND U.bDisable = 0 AND IFNULL(C.bDelete, 0) = 0 AND IFNULL(C.bHistory, 0) = 0 AND C.bImport <> 0 AND C.bSplitLock = 0')
                ->andWhere(
                    'U.iSchoolId = :schoolId: AND C.iChargeYear = :chargeYear: AND C.iSumDues = :sumDues: AND C.iSumCost = :sumCost:',
                    ['schoolId' => $data['schoolId'], 'chargeYear' => $data['iChargeYear'], 'sumDues' => $data['iSumDues'], 'sumCost' => $data['iSumCost']]
                )
                ->getQuery()
                ->execute();
            $chargeIdArr = $chargeIdArr->toArray();
            if (!$chargeIdArr) {
                return $this->sendErrorResponse(400, '无匹配记录');
            }
            $chargeIdArr = array_column($chargeIdArr, 'iCCId');
            $chargeIds   = implode(',', $chargeIdArr);
//            $timeUpdate  = '';
//            if ($data['iSerYear']) {
//                $timeUpdate = ", tExpireTime = DATE_ADD(tChargeTime, INTERVAL {$data['iSerYear']} YEAR)";
//            }
            $updateSql = "UPDATE XHCost_StudCharge SET bSplitLock = 1, iDevCost = '{$data['iDevCost']}', iDeposit = '{$data['iDeposit']}', iRentCost = '{$data['iRentCost']}', 
                            iSerCost = '{$data['iSerCost']}', iSerYear = '{$data['iSerYear']}', tStartTime = '{$data['tStartTime']}', tExpireTime = '{$data['tExpireTime']}' WHERE iCCId IN ({$chargeIds})";
            $result = $this->db->execute($updateSql);
            if (!$result) {
                return $this->sendErrorResponse(500, '拆分失败');
            }
            return $this->sendSuccessResponse('成功拆分' . count($chargeIdArr) . '条记录');
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, '拆分失败', $e->getMessage());
        }
    }

    /**
     * 批量拆分
     *
     * @param $data
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171213
     */
    private function splitStudCharge($data)
    {
        $ids = explode(',', $data['ids']);
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少缴费id');
        }
        try {
            $chargeIds   = implode(',', $ids);
//            $timeUpdate  = '';
//            if ($data['iSerYear']) {
//                $timeUpdate = ", tExpireTime = DATE_ADD(tChargeTime, INTERVAL {$data['iSerYear']} YEAR)";
//            }
            $updateSql = "UPDATE XHCost_StudCharge SET bSplitLock = 1, iDevCost = '{$data['iDevCost']}', iDeposit = '{$data['iDeposit']}', iRentCost = '{$data['iRentCost']}', 
                            iSerCost = '{$data['iSerCost']}', iSerYear = '{$data['iSerYear']}', tStartTime = '{$data['tStartTime']}', tExpireTime = '{$data['tExpireTime']}' WHERE iCCId IN ({$chargeIds})";
            $result = $this->db->execute($updateSql);
            if (!$result) {
                return $this->sendErrorResponse(500, '拆分失败');
            }
            return $this->sendSuccessResponse('成功拆分' . count($ids) . '条记录');
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, '拆分失败', $e->getMessage());
        }
    }

    /**
     * 导入excel缴费信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170808
     * modify by ck 20170926    更改文件上传方式，添加额外信息
     * modify by ck 20171205    可导入手动收费信息
     * modify by ck 20180110    添加班级名称格式判断
     * modify by ck 20180122    根据应缴不同可导入多条记录
     * modify by ck 20180226    区分缴费导入时间|交易时间
     * modify by ck 20180615    添加字段
     * modify by ck 20180905
     */
    public function importChargeFileAction()
    {
        return $this->sendErrorResponse(403, '该功能维护中...');
        $chargeYear = $this->request->getPost('chargeYear', 'int');
        $schoolId   = $this->request->getPost('schoolId', 'int');
        $type       = $this->request->getPost('type', 'int');   //1=账号导入，2=手动导入，3=流水
        $createNew  = !!$this->request->getPost('createNew', 'string') == 'true';
        $autoClass  = $this->request->getPost('autoClass', 'int');
        $schoolName = XhschoolInfo::getSchoolArray()[$schoolId];
        $file       = $this->request->getUploadedFiles()[0];
        if (!$chargeYear || !$file) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        if (!School::isApproval($schoolId)) {
            return $this->sendErrorResponse(400, '该学校未审核，无法导入');
        }
        $fileName   = $file->getName();

        if (Tool::isWindows()) {
            $fileName = iconv('utf-8', 'GBK', $fileName);
        }
        $filePath = Tool::buildPath(TEMP_PATH, $fileName);
        $file->moveTo($filePath);

        //读取数据并写入数据库
        $this->db->begin();
        $importNum = $totalNum = 0;
        $errorUser = $newUser  = $classInfo = [];
        try {
            $result     = Tool::readExcel($filePath, true);
            $titleArr   = $result['title'];
            $rows       = $result['data'];
            $nowTime    = date('Y-m-d H:i:s');
            $annualCost = Main::getConfigByName('studCharge')['annualCost'] ?: 360;
            @unlink($filePath);

            //检查必要参数是否存在，并替换其index值
            $mainIndex = ['name' => '姓名'];
            switch ($type) {
                case 1:
                    $mainIndex += ['code' => '缴费编号', 'dues' => '应缴总额', 'cost' => '实缴总额', 'class' => '班级'];
                    break;
                case 2:
                    $mainIndex += ['school' => '学部', 'dues' => '应缴总额', 'cost' => '实缴总额'];
                    break;
                case 3:
                    $mainIndex += ['code' => '缴费编号', 'dues' => '发生金额', 'cost' => '发生金额'];
                    break;
                default:
                    return $this->sendErrorResponse(400, '导入类型不正确');
            }
            foreach ($mainIndex as $key => $name) {
                $index = array_search($name, $titleArr);
                if ($index === false) {
                    return $this->sendErrorResponse(400, "缺少[{$name}]项信息");
                }
                $mainIndex[$key] = $index;
            }

            //判断学校名称
            if (in_array($type, [1, 2])) {
                foreach ($rows as $row) {
                    if ($row[$mainIndex['school']] && $row[$mainIndex['school']] != $schoolName) {
                        return $this->sendErrorResponse(400, '学校名称有误或不统一', $row);
                    }
                    if ($type == 1 && $row[$mainIndex['class']]) {
                        if (!is_numeric($row[$mainIndex['class']]) || strlen($row[$mainIndex['class']]) !== 4) {
                            return $this->sendErrorResponse(400, '班级名称不正确，请确认', $row);
                        }
                    }
                }
            }

            //检查额外参数是否存在，存在则替换index，过滤并写入数据库
            $extraIndex = [
                'iDevCost'   => '设备费',
                'iDeposit'   => '押金',
                'iRentCost'  => '租金',
                'iSerCost'   => '服务费',
                'iSerYear'   => '服务年限',
                'tChargeTime'=> '交易时间',
            ];
            foreach ($extraIndex as $key => $name) {
                $extraIndex[$key] = array_search($name, $titleArr);
            }
            $extraIndex = array_filter($extraIndex);

            $userExtra = [
                'iUserSex'      => '性别',
                'sIdentityCode' => '证件号',
                'sMotherName'   => '母亲姓名',
                'sMotherPhone'  => '母亲电话',
                'sFatherName'   => '父亲姓名',
                'sFatherPhone'  => '父亲电话',
                'sOtherName'    => '监护人姓名',
                'sOtherPhone'   => '监护人电话',
                'pClass'        => '培优班'
            ];
            foreach ($userExtra as $key => $name) {
                $userExtra[$key] = array_search($name, $titleArr);
            }
            $userExtra = array_filter($userExtra);

            foreach ($rows as $row) {
                //缺少参数则跳过
                if (in_array($type, [1, 3]) && !$row[$mainIndex['code']]) {
                    continue;
                } elseif ($type == 2 && !$row[$mainIndex['name']]) {
                    continue;
                }

                $totalNum++;
                //检查用户是否存在或多个
                try {
                    switch ($type) {
                        case 1:
                            $row[$mainIndex['code']] = trim($row[$mainIndex['code']]);
                            $userId = $this->getStudIdByCode($row[$mainIndex['code']], $schoolId);
                            break;
                        case 2:
                            $userId = $this->getStudIdByName($row[$mainIndex['name']], $schoolId);
                            break;
                        case 3:
                            $row[$mainIndex['code']] = trim($row[$mainIndex['code']]);
                            $userId = $this->getStudIdByCode($row[$mainIndex['code']]);
                            break;
                        default: continue 2;
                    }

                }
                catch (\Exception $e) {
                    //新建账号
                    if ($e->getMessage() == '用户不存在' && $type == 1 && $createNew) {
                        try {
                            $this->db->begin();
                            $user = new XhsysUser();
                            $user->sLogonName   = $row[$mainIndex['code']];
                            $user->sUserName    = $row[$mainIndex['name']];
                            $user->sAdClsName   = $row[$mainIndex['class']];
                            $user->sLogonPwd    = strtoupper(md5('123456'));
                            $user->iSchoolId    = $schoolId;
                            $user->iUserType    = 1;
                            if (isset($userExtra['iUserSex'])) {
                                $user->iUserSex = $row[$userExtra['iUserSex']] == '男' ? 1 : ($row[$userExtra['iUserSex']] == '女' ? 2 : 0);
                            }
                            foreach (['sMotherPhone', 'sFatherPhone', 'sOtherPhone', 'sIdentityCode'] as $key) {
                                if (isset($userExtra[$key])) {
                                    $user->$key = $row[$userExtra[$key]];
                                }
                            }
                            if (!$user->insertAfterOld(true)) {
                                throw new \Exception($user->getError());
                            }
                            $userId = $user->iUserId;
                            $stud = new XhsysUserstud();
                            $stud->iUserId = $userId;
                            foreach (['sMotherName', 'sFatherName', 'sOtherName'] as $key) {
                                if (isset($userExtra[$key])) {
                                    $stud->$key = $row[$userExtra[$key]];
                                }
                            }
                            $stud->save();
//                            $userId = $this->createNewStudAccount($schoolId, $row[$mainIndex['code']], $row[$mainIndex['name']], $row[$mainIndex['class']]);
                            $newUser[] = ['id' => $userId, 'name' => $row[$mainIndex['name']], 'code' => $row[$mainIndex['code']]];

                            //处理新增班级信息
                            switch ($autoClass) {
                                case 1:
                                    if ($row[$mainIndex['class']]) {
                                        $classInfo[$row[$mainIndex['class']]][] = $userId;
                                    }
                                    break;
                                case 2:
                                    if (isset($userExtra['pClass']) && $row[$userExtra['pClass']]) {
                                        $classInfo[$row[$userExtra['pClass']]][] = $userId;
                                    }
                                    break;
                            }
//                            if ($row[$mainIndex['class']]) {
//                                $classInfo[$row[$mainIndex['class']]][] = $userId;
//                            }
                            $this->db->commit();
                        }
                        catch (\Exception $e) {
                            $this->db->rollback();
                            $errorUser[] = ['name' => $row[$mainIndex['name']], 'code' => $type == 2 ? '' : $row[$mainIndex['code']], 'reason' => '创建失败：' . $e->getMessage()];
                            continue;
                        }
                    }
                    else {
                        $errorUser[] = ['name' => $row[$mainIndex['name']], 'code' => $type == 2 ? '' : $row[$mainIndex['code']], 'reason' => $e->getMessage()];
                        continue;
                    }
                }

                //检查是否已手动导入
                $check = XhcostStudcharge::count([
                    'conditions' => 'iStudId = :userId: AND iChargeYear = :chargeYear: AND bDelete = 0 AND bImport = 0',
                    'bind'       => ['userId' => $userId, 'chargeYear' => $chargeYear]
                ]);
                if ($check) {
                    $errorUser[] = ['name' => $row[$mainIndex['name']], 'code' => $type == 2 ? '' : $row[$mainIndex['code']], 'reason' => '该年份已有手动录入记录'];
                    continue;
                }

                //获取原导入记录
                $charge = XhcostStudcharge::findFirst([
                    'conditions' => 'iStudId = :userId: AND iChargeYear = :chargeYear: AND bDelete = 0 AND iSumDues = :sumDues:',
                    'bind'       => ['userId' => $userId, 'chargeYear' => $chargeYear, 'sumDues' => $row[$mainIndex['dues']]]
                ]);

                //无信息则新建
                if (!$charge) {
                    //流水导入则报错
                    if ($type == 3) {
                        $errorUser[] = ['name' => $row[$mainIndex['name']], 'code' => $type == 2 ? '' : $row[$mainIndex['code']], 'reason' => '无应缴数据记录'];
                        continue;
                    }
                    $charge = new XhcostStudcharge();
                    $charge->iStudId     = $userId;
                    $charge->iChargeYear = $chargeYear;
                    $charge->tChargeImportTime  = $nowTime;
                    $charge->bImport            = $type == 2 ? 2 : 1;
                    $charge->iState             = 4;
                }

                //已缴费数额不同则更新缴费导入时间
                if ($charge->iSumCost != $row[$mainIndex['cost']]){
                    $charge->iSumCost           = $row[$mainIndex['cost']];
                    $charge->tChargeImportTime  = $nowTime;
                }
                isset($mainIndex['dues']) and $charge->iSumDues = $row[$mainIndex['dues']];

                //更新额外信息
                $extraCost = 0;
                foreach ($extraIndex as $field => $index) {
                    if ($field == 'tChargeTime') {
                        $charge->$field = $row[$index] ? date('Y-m-d H:i:s', strtotime($row[$index])) : null;
                        continue;
                    }
                    if (in_array($field, ['iDevCost', 'iDeposit', 'iRentCost', 'iSerCost'])) {
                        $extraCost += $row[$index];
                    }
                    $charge->$field = $row[$index];
                }
                if ($charge->iSerCost && !$charge->iSerYear) {
                    $charge->iSerYear    = ceil($charge->iSerCost / $annualCost);
                    $charge->tExpireTime = date('Y-m-d H:i:s', strtotime("+{$charge->iSerYear} year", strtotime($charge->tChargeTime)));
                }

                //有缴费且拆分信息等于缴费则锁定
                if ($charge->iSumCost > 0 && $charge->iSumCost == $extraCost) {
                    $charge->bSplitLock = 1;
                }

                if (!$charge->save()){
                    $errorUser[] = ['name' => $row[$mainIndex['name']], 'code' => $row[$mainIndex['code']], 'reason' => '保存失败'];
                    continue;
                }
                $importNum++;
            }
            $this->db->commit();
        }
        catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        $msg = "成功导入{$importNum}条！（共{$totalNum}条）";
        if ($newUser) {
            $msg .= '。创建新账号：' . count($newUser) . '个';
            if ($classInfo) {
                try {
                    UserService::initStudClass($schoolId, $classInfo, $autoClass - 1);
                } catch (\Exception $e) {
                }
            }
        }
        return $this->sendJsonResponse([
            'msg'       => $msg,
            'errorData' => $errorUser,
            'newUser'   => $newUser
        ], true);
    }

    /**
     * 导出学生收费数据
     *
     * @return string
     *
     * create by ck 20180227
     */
    public function exportStudChargeAction()
    {
        $this->view->disable();
        $title = Template::getXmlFields('Cost_StudCharge');
        $data  = $this->getStudChargeAction(true);
        if (!$data) {
            return $this->sendViewError('无数据可导出');
        }
        $keys = array_keys($title);
        foreach ($data as &$row) {
            $temp = [];
            foreach ($keys as $key) {
                $temp[$key] = $row[$key];
            }
            $row = $temp;
        }
        Tool::exportExcelOnline('收费信息', array_values($title), $data);
    }

    /**
     * 根据身份证号获取学生id
     *
     * @param $code
     * @param null $schoolId
     * @return string
     * @throws \Exception
     *
     * create by ck 20171221
     * modify by ck 20180914    添加重复检查
     */
    private function getStudIdByCode($code, $schoolId = null)
    {
        $params = [
            'columns'    => 'iUserId,iSchoolId',
            'conditions' => 'bDelete = 0 AND bDisable = 0 AND (sLogonName = :code: OR sIdentityCode = :code:)',
            'bind'       => ['code' => $code]
        ];
        $users = XhsysUser::find($params);
        if (count($users) <= 0) {
            throw new \Exception('用户不存在', 404);
        } elseif (count($users) > 1) {
            throw new \Exception('该用户重复');
        }
        $user = $users[0];
        if ($schoolId && $user->iSchoolId != $schoolId) {
            throw new \Exception('该账号学校不匹配');
        }
        return $user->iUserId;
    }

    /**
     * 根据姓名及学校获取学生id
     *
     * @param $name
     * @param null $schoolId
     * @return string
     * @throws \Exception
     *
     * create by ck 20171221
     */
    private function getStudIdByName($name, $schoolId = null)
    {
        $params = [
            'columns'    => 'iUserId',
            'conditions' => 'bDelete = 0 AND bDisable = 0 AND bHistory = 0 AND iUserType = 1 AND sUserName = :name:',
//            'conditions' => 'bDelete = 0 AND bDisable = 0 AND bCompany = 0 AND bHistory = 0 AND iUserType = 1 AND sUserName = :name:',
            'bind'       => ['name' => $name]
        ];
        if ($schoolId) {
            $params['conditions'] .= ' AND iSchoolId = :schoolId:';
            $params['bind']['schoolId'] = $schoolId;
        }
        $users = XhsysUser::find($params);
        if (count($users) > 1) {
            throw new \Exception('用户重复');
        }
        else if (count($users) < 1) {
            throw new \Exception('无此用户');
        }
        return $users[0]->iUserId;
    }

    /**
     * 创建新学生账号
     *
     * @param $schoolId
     * @param $logonName
     * @param $userName
     * @param $className
     * @return int
     * @throws \Exception
     *
     * create by ck 20171225
     */
//    private function createNewStudAccount($schoolId, $logonName, $userName, $className)
//    {
//        static $oldDB, $schoolDB, $nowTime, $password, $first = true;
//        if ($first) {
//            $dbName    = '';
////            $oldDBName = Main::getConfigByName('oldCenterDB')['dbname'];
//            $oldConfig = Main::getConfigByName('oldCenterDB');
//            $oldConfig['username'] = 'webmail_user';//$this->config->get('database')['username'];
//            $oldConfig['password'] = 'szw_webmail1234';//$this->config->get('database')['password'];
//            $oldDB     = new Mysql($oldConfig);
//            $schoolDB  = Main::getSchoolMainDB($schoolId, $dbName);
//            $first     = false;
//            $nowTime   = date('Y-m-d H:i:s');
//            $password  = strtoupper(md5('123456'));
//        }
//        if (!$oldDB) {
//            throw new \Exception('老数据中心连接失败');
//        }
//        if (!$schoolDB) {
//            throw new \Exception('学校库连接失败');
//        }
//        $extraField = [
//            'us_csrq' => '0000-00-00',
//            'us_tel' => '',
//            'us_xb' => '',
//            'us_mz' => '',
//            'us_bmdq' => '',
//            'us_sdxx' => '',
//            'us_sdnj' => '',
//            'us_qq' => '',
//            'us_fmxm' => '',
//            'us_jtgddh' => '',
//            'us_fmsj' => '',
//            'us_jtdz' => '',
//            'us_fmdw' => '',
//            'us_dwdz' => '',
//            'us_bzsm' => '',
//            'us_ord' => 0,
//            'us_sskm' => '',
//            'us_lastip' => '',
//            'us_question' => '',
//            'us_answer' => '',
//            'us_lxxx' => '',
//            'us_gsbz' => '',
//            'us_us_id_power' => '',
//            'us_province' => '',
//            'us_city1' => '',
//            'us_city2' => '',
//            'us_fw_text' => '',
//            'us_fdq_name' => '',
//            'us_sfzx' => '',
//            'us_us_id_power_ls' => '',
//            'us_jf_dates' => '0000-00-00 00:00:00',
//            'us_sq_dl_dates' => '0000-00-00 00:00:00',
//            'us_sq_ls_dates' => '0000-00-00 00:00:00',
//            'us_sales_sort' => '',
//            'us_sq_fl_dates' => '0000-00-00 00:00:00',
////            'us_szbj' => '',
//            'us_fmsjm' => '',
//            'us_xyh' => '',
//            'us_domain' => '',
//            'us_nickname' => '',
//            'us_email' => '',
//            'us_czy_id' => 0,
//        ];
//        $oldCenterResult = $oldDB->insert(
//            'users',
//            array_merge([$logonName, $userName, 1, $schoolId, $password, $nowTime, $className], array_values($extraField)),
//            array_merge(['us_uid', 'us_name', 'us_flag', 'us_school_xxid', 'us_passwd', 'us_date', 'us_szbj'], array_keys($extraField))
//        );
////        $oldCenterResult = $this->db->execute("insert into {$oldDBName}.users (us_uid,us_name,us_flag,us_school_xxid,us_passwd,us_date) values ('{$logonName}','{$userName}',1,'{$schoolId}','{$password}','{$nowTime}')");
//        if (!$oldCenterResult) {
//            throw new \Exception('老数据中心插入失败');
//        }
//        $userId = $oldDB->lastInsertId();
//        $error = [];
//        $schoolResult = $schoolDB->insert(
//            'users',
//            array_merge([$logonName, $userName, 1, $schoolId, $password, $nowTime, $className, $userId], array_values($extraField)),
//            array_merge(['us_uid', 'us_name', 'us_flag', 'us_school_xxid', 'us_passwd', 'us_date', 'us_szbj', 'us_id'], array_keys($extraField))
//        );
////        $schoolResult = $schoolDB->execute("insert into users (us_uid,us_name,us_flag,us_school_xxid,us_passwd,us_date,us_id) values ('{$logonName}','{$userName}',1,'{$schoolId}','{$password}','{$nowTime}','{$userId}')");
//        if (!$schoolResult) {
//            $error[] = '学校数据库插入失败';
//        }
//        $user = new XhsysUser();
//        $user->iUserId      = $userId;
//        $user->sLogonName   = $logonName;
//        $user->sUserName    = $userName;
//        $user->iSchoolId    = $schoolId;
//        $user->iUserType    = 1;
//        $user->sLogonPwd    = $password;
//        $user->sAdClsName   = $className;
//        $user->sRoles       = XhsysUser::getRoles(1);
//        if (!$user->save()) {
//            $error[] = '数据中心保存失败';
//        }
//        if ($error) {
//            throw new \Exception(implode(',', $error));
//        }
//        return $userId;
//    }

    /**
     * 更改记录状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170823
     */
    public function modifyStudChargeStateAction()
    {
        $id    = $this->request->getPost('id', 'int');
        $state = $this->request->getPost('state', 'int');
        if (!$id || !$state) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        switch ($state) {
            case 2:  $power = Power::exist('Cost_StudCharge_Edit'); break;
            case 1:
            case 3:  $power = Power::exist('Cost_StudCharge_Audit'); break;
            default: $power = false;
        }
        if (!$power) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        $charge = XhcostStudcharge::findFirst($id);
        if (!$charge) {
            return $this->sendErrorResponse(400, '找不到该记录');
        }
        if ($charge->bImport != 0) {
            return $this->sendErrorResponse(400, '无法操作导入数据');
        }
        $charge->iState = $state;
        if (!$charge->save()) {
            return $this->sendErrorResponse(500, '操作失败');
        }
        return $this->sendSuccessResponse('操作成功');
    }

    /**
     * 解锁状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170926
     */
    public function unlockStudChargeSplitAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        $updateSql = "UPDATE \\Admin\\Models\\cost\\XhcostStudcharge SET bSplitLock = 0 WHERE iCCId IN ({ids:array})";
        $result = $this->modelsManager->executeQuery($updateSql, ['ids' => $ids]);
        if (!$result) {
            return $this->sendErrorResponse(500, '解锁失败');
        }
        return $this->sendSuccessResponse('解锁成功');
    }

    /**
     * 删除缴费记录
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171019
     */
    public function delStudChargeAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if(!$ids){
            return $this->sendErrorResponse(400, 'id不能为空');
        }
        $result = XhcostStudcharge::deleteRecord('iCCId', $ids);
        return $result ? $this->sendSuccessResponse('删除成功') : $this->sendErrorResponse('删除失败');
    }

    /**
     * 学校收费统计
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180620
     */
    public function schoolChargeAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/cost/schoolCharge.js');
        if (!Power::exist('costStats1')) {
            return $this->sendViewError('无查看权限');
        }

        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_year', 'style' => 'width:80px;', 'data' => $this->getYearEnum(), 'default' => date('Y')];
        $enums['province'] = array_column(array_values($this->getAreaByLevel(1)),'areaName','areaCode');
        $enums['province'][''] = '--请选择省--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_province', 'data' => $enums['province'], 'default' => '');
        $enums['city'][''] = '--请选择市--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_city', 'data' => $enums['city'], 'default' => '');
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'list_depart', 'style' => 'width:120px;'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_export', 'text' => '导出', 'icon' => 'fa fa-file-excel-o'];
        return $this->view->setVars([
            'List'  => Template::createList('list', 'Cost_ChargeStats1', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ]);
    }

    /**
     * 获取省份
     *
     * @param $level
     * @return array
     */
    public function getAreaByLevel($level){
        $area = XhovertAreainfo::find([
            'conditions' => ' areaLevel = :level:',
            'bind'       => ['level'=> $level ]
        ])->toArray();
        $area = array_column($area,null,'areaCode');
        return $area;
    }

    /**
     * 获取学校收费统计数据
     *
     * @param $return
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by ck 20180620
     * modify by ck 20180620    可根据缴费时间搜索，添加总计
     * modify by ck 20180926    重构
     * modify by sqb 20181219   新增筛选条件
     */
    public function getSchoolChargeAction($return = false)
    {
        if (!Power::exist('costStats1')) {
            return $this->sendErrorResponse(403, '无查看权限');
        }
        $page = $this->request->getPost('page', 'int');
        $rows = $this->request->getPost('rows', 'int');
        $year = $this->request->get('year', 'int');
        $province = $this->request->get('province', 'int');
        $city = $this->request->get('city', 'int');
        $depart = $this->request->get('depart', 'int');

        try {
            $where = [];
            if ($province) {
                $province = XhovertAreainfo::getNameByCode($province);
                $where['province'] = $province;
            }

            if ($city) {
                $city = XhovertAreainfo::getNameByCode($city);
                $where['city'] = $city;
            }

            $schools = School::getPower(true);
            if ($schools === true) {
                $schools = School::getSchoolsByArea($where);
            }

            if ($depart) {
                $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depart},%'");
                $authId = $staff['iUserId'];
                if (!$authId) {
                    return $this->sendJsonResponse([]);
                }
                $schoolArr = User::getSchool(true, $authId, true);
                if (!empty($schoolArr)){
                    $schoolIds = implode(',', array_keys($schoolArr));
                    $schoolList = XhschoolInfo::find([
                        'conditions' => "bDelete = 0 AND (iStatus = 1 OR iStatus = 2) AND iSchoolId in ({$schoolIds})",
                        'columns'    => 'iSchoolId,sSchoolName',
                    ])->toArray();
                    $schools = array_column($schoolList, 'sSchoolName', 'iSchoolId');
                }
            }

            $data = [
                'total' => count($schools),
                'rows'  => []
            ];
            if ($page && $rows) {
                $schools = array_slice($schools, $rows * ($page - 1), $rows, true);
            }

            if (!$schools) {
                return $this->sendJsonResponse([]);
            }
            $schoolIds = array_keys($schools);
            $schoolIdStr = implode(',', $schoolIds);
            $sql = "SELECT u.iSchoolId, SUM(c.receivable) AS receivable,
                  SUM(c.received) AS received, SUM(c.receivable - c.received) as notReceived,
                  SUM(c.received > c.receivable) as overPay,
                  SUM(c.receivable > 0) AS totalNum, SUM(c.receivable > 0 and c.receivable = c.received) AS payNum,
                  SUM(c.receivable > c.received) AS notPayNum
                FROM XHCost_Charge AS c
                LEFT JOIN XHSys_User AS u ON c.userId = u.iUserId
                WHERE c.bDelete = 0 AND u.bDelete = 0 AND c.year = '{$year}' AND u.iSchoolId IN ({$schoolIdStr})
                GROUP BY u.iSchoolId";
            $rows = $this->db->fetchAll($sql);
            $rows = array_column($rows, null, 'iSchoolId');
            foreach ($schools as $schoolId => $schoolName) {
                $data['rows'][] = array_merge(['iSchoolId' => $schoolId, 'sSchoolName' => $schoolName], Tool::getValue($rows, $schoolId, []));
            }
            School::runCode($data['rows'], ['iSchoolId' => 'sCode']);
            return $return ? $data['rows'] : $this->sendJsonResponse($data);
        }
        catch (\Exception $e) {
            if ($return) {
                throw new \Exception($e->getMessage());
            }
            return $this->sendErrorResponse(500, $e->getMessage());
        }

//        $page       = $this->request->getPost('page', 'int');
//        $rows       = $this->request->getPost('rows', 'int');
//        $mode       = $this->request->get('mode', 'int');
//        $year       = $this->request->get('year', 'int');
//        $startTime  = $this->request->get('startTime', 'string');
//        $endTime    = $this->request->get('endTime', 'string');
//        $schools    = School::getPower(true);
//        if ($schools === true) {
//            $schools = School::getSchools();
//        }
//        $data = [
//            'total' => count($schools),
//            'rows'  => []
//        ];
//        if ($page && $rows) {
//            $schools = array_slice($schools, $rows * ($page - 1), $rows, true);
//        }
//        if (!$schools) {
//            return $this->sendDataGridError('无数据');
//        }
//        $schoolIds = array_keys($schools);
//        try {
//            $builder = $this->modelsManager->createBuilder()
//                ->columns('u.iSchoolId as iSchoolId,sum(c.iSumDues) as iSumDues,sum(c.iSumCost) as iSumCost,
//                    sum(c.iSumDues)-sum(c.iSumCost) as iSumNotPay,sum(c.iDevCost) as iDevCost,sum(c.iSerCost) as iSerCost,
//                    sum(c.iDeposit) as iDeposit,sum(c.iRentCost) as iRentCost, count(c.iStudId) as totalNum,
//                    sum(IFNULL(c.iSumDues,0) = IFNULL(c.iSumCost,0)) as payNum,sum(IFNULL(c.iSumDues,0) <> IFNULL(c.iSumCost,0)) as notPayNum')
//                ->from(['c' => '\\Admin\\Models\\cost\\XhcostStudcharge'])
//                ->leftJoin('\\Admin\\Models\\user\\XhsysUser', 'c.iStudId = u.iUserId', 'u')
//                ->where('u.bDisable = 0 AND u.bDelete = 0 AND u.bHistory = 0 AND c.bDelete = 0');
//            //根据年度
//            if ($mode == 1) {
//                if ($year) {
//                    $builder->andWhere('c.iChargeYear = :year:', ['year' => $year]);
//                }
//            }
//            //根据时间
//            else if ($mode == 2) {
//                if ($startTime) {
//                    $builder->andWhere('c.tChargeTime >= :startTime:', ['startTime' => $startTime]);
//                }
//                if ($endTime) {
//                    $endTime = date('Y-m-d', strtotime($endTime . ' +1 day'));
//                    $builder->andWhere('c.tChargeTime <= :endTime:', ['endTime' => $endTime]);
//                }
//            }
//            $total = $builder->getQuery()->execute()->toArray()[0];
//            $builder->andWhere('u.iSchoolId IN ({schoolIds:array})', ['schoolIds' => $schoolIds]);
//            $current = $builder->getQuery()->execute()->toArray()[0];
//            $builder->groupBy('u.iSchoolId');
//            $rows = $builder->getQuery()->execute()->toArray();
//            $rows = array_column($rows, null, 'iSchoolId');
//            foreach ($schools as $schoolId => $schoolName) {
//                $data['rows'][] = array_merge(['iSchoolId' => $schoolId, 'sSchoolName' => $schoolName], Tool::getValue($rows, $schoolId, []));
//            }
//
//            if ($return) {
//                return $data['rows'];
//            }
//            unset($total['iSchoolId'], $current['iSchoolId']);
//            $current['sSchoolName'] = '当前合计';
//            $total['sSchoolName']   = '总计';
//            $data['footer']         = [$current, $total];
//            return $this->sendJsonResponse($data);
//        }
//        catch (\Exception $e) {
//            if ($return) {
//                throw new \Exception($e->getMessage());
//            }
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
    }

    /**
     * 学校缴费明细
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180621
     * modify by ck 20180926    重构
     */
    public function schoolChargeDetailAction()
    {
        $schoolId   = $this->request->getQuery('schoolId', 'int');
        $year       = $this->request->getQuery('year', 'string');
        if (!$schoolId || !$year) {
            return $this->sendViewError('缺少参数');
        }
        $this->view->pick('cost/schoolChargeDetail');
        try {
            $sql = "SELECT c.receivable, SUM(c.receivable) AS totalReceivable, SUM(c.received) AS totalReceived,
                      SUM(c.receivable - c.received) AS notReceived, SUM(c.receivable > 0) AS totalNum,
                      SUM(c.receivable > 0 AND c.receivable = c.received) AS payNum,
                      SUM(c.receivable > c.received) AS notPayNum
                    FROM XHCost_Charge AS c
                    LEFT JOIN XHSys_User AS u ON c.userId = u.iUserId
                    WHERE c.bDelete = 0 AND u.bDelete = 0 AND u.iSchoolId = '{$schoolId}'
                    GROUP BY c.receivable";
            $rows = $this->db->fetchAll($sql);
            return $this->view->setVars([
                'rows' => $rows
            ]);
        }
        catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }

//        $schoolId   = $this->request->getQuery('schoolId', 'int');
//        $chargeYear = $this->request->getQuery('chargeYear', 'string');
//        $startTime  = $this->request->getPost('startTime', 'string');
//        $endTime    = $this->request->getPost('endTime', 'string');
//        if (!$schoolId) {
//            return $this->sendViewError('缺少学校id');
//        }
//        $this->view->pick('cost/schoolChargeDetail');
//        try {
//            $builder = $this->modelsManager->createBuilder()
//                ->columns('c.iSumDues as sumDues,sum(c.iSumDues) as iSumDues,sum(c.iSumCost) as iSumCost,sum(c.iSumDues)-sum(c.iSumCost) as iSumNotPay,
//                    sum(c.iDevCost) as iDevCost,sum(c.iSerCost) as iSerCost,sum(c.iDeposit) as iDeposit,sum(c.iRentCost) as iRentCost,
//                    count(c.iStudId) as totalNum,sum(IFNULL(c.iSumDues,0) = IFNULL(c.iSumCost,0)) as payNum,sum(IFNULL(c.iSumDues,0) <> IFNULL(c.iSumCost,0)) as notPayNum')
//                ->from(['c' => '\\Admin\\Models\\cost\\XhcostStudcharge'])
//                ->leftJoin('\\Admin\\Models\\user\\XhsysUser', 'c.iStudId = u.iUserId', 'u')
////                ->where('u.bDisable = 0 AND u.bDelete = 0 AND u.bHistory = 0 AND c.bDelete = 0')
//                ->where('u.bDelete = 0 AND c.bDelete = 0')
//                ->andWhere('u.iSchoolId = :schoolId:', ['schoolId' => $schoolId])
//                ->groupBy('c.iSumDues');
//            if ($chargeYear) {
//                $builder->andWhere('c.iChargeYear = :chargeYear:', ['chargeYear' => $chargeYear]);
//            }
//            if ($startTime) {
//                $builder->andWhere('c.tChargeTime >= :startTime:', ['startTime' => $startTime]);
//            }
//            if ($endTime) {
//                $builder->andWhere('c.tChargeTime <= :endTime:', ['endTime' => $endTime]);
//            }
//            $rows = $builder->getQuery()->execute()->toArray();
//            return $this->view->setVars([
//                'rows' => $rows
//            ]);
//        }
//        catch (\Exception $e) {
//            return $this->sendViewError($e->getMessage());
//        }
    }

    /**
     * 导出学校收费统计
     *
     * @return string
     *
     * create by ck 20180622
     * modify by ck 20181122
     */
    public function exportSchoolChargeAction()
    {
        try {
            $data  = $this->getSchoolChargeAction(true);
            $title = [
                'sCode'         => '学校编号',
                'sSchoolName'   => '学校',
                'receivable'    => '应缴总额',
                'totalNum'      => '应缴人次',
                'received'      => '实缴总额',
                'payNum'        => '实缴人次',
                'notReceived'   => '未缴总额',
                'notPayNum'     => '未缴人次',
                'overPay'       => '异常缴人交'
            ];
            $data = Tool::runExcelData($title, $data);
            $fileName = '收费统计1';
            $this->view->disable();
            Tool::exportExcelOnline($fileName, $title, $data, 'xlsx', ['autoWidth' => true]);
        }
        catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 收费统计2
     *
     * @return \Phalcon\Mvc\View
     *
     * create by ck 20180816
     */
    public function chargeStatsAction()
    {
        if (!Power::exist('costStats2')) {
            return $this->sendViewError('无查看权限');
        }
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/cost/chargeStats.js');
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_year', 'style' => 'width:80px;', 'label' => '年度：',
            'data' => $this->getYearEnum(), 'default' => date('Y')];
//        $listSearchArr[] = ['type' => 'select', 'id' => 'list_type', 'style' => 'width:80px;', 'label' => ' 项目：', 'data' => [
//            1 => '-全部-',
//            2 => '服务费',
//            3 => '设备费',
//            4 => '押金',
//            5 => '设备费+押金'
//        ]];

        $enums['province'] = array_column(array_values($this->getAreaByLevel(1)),'areaName','areaCode');
        $enums['province'][''] = '--请选择省--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_province', 'data' => $enums['province'], 'default' => '');
        $enums['city'][''] = '--请选择市--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_city', 'data' => $enums['city'], 'default' => '');
        $listSearchArr[] = ['label' => ' ', 'type'=>'select', 'id'=>'list_depart', 'style' => 'width:120px;'];

        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_export', 'text' => '导出', 'icon' => 'fa fa-file-excel-o'];
        //        $listButtonArr[] = ['id' => 'bt_list_jump', 'text' => '收费详情', 'icon' => 'fa-arrow-circle-right'];
        return $this->view->setVars([
            'List'  => Template::createList('list', 'Cost_ChargeStats2', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ]);
    }

    /**
     * 获取收费统计2信息
     *
     * @param $return
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by ck 20180816
     * modify by ck 20180926    重构
     * modify by ck 20181016    更改学校编码
     * modify by sqb 20181220   添加筛选条件
     */
    public function getChargeStatsAction($return = false)
    {
        if (!Power::exist('costStats2')) {
            return $this->sendErrorResponse(403, '无查看权限');
        }
        $year = $this->request->get('year', 'int');
        if (!$year) {
            return $this->sendErrorResponse(400, '缺少年份');
        }

        $province = $this->request->get('province', 'int');
        $city = $this->request->get('city', 'int');
        $depart = $this->request->get('depart', 'int');

        try {
            $where = [];
            $conditions = '';
            if ($province) {
                $province = XhovertAreainfo::getNameByCode($province);
                $where['province'] = $province;
            }

            if ($city) {
                $city = XhovertAreainfo::getNameByCode($city);
                $where['city'] = $city;
            }
            $schools = School::getPower(true);
            if ($schools === true) {
                $schools = School::getSchoolsByArea($where);
                if ($schools) {
                    $schoolIdStr = implode(',', array_keys($schools));
                    $conditions  = " AND u.iSchoolId IN ({$schoolIdStr})";
                } else {
                    return $this->sendJsonResponse([]);
                }
            }

            if ($depart) {
                $staff  = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depart},%'");
                $authId = $staff['iUserId'];
                if (!$authId) {
                    return $this->sendJsonResponse([]);
                }
                $schoolArr = User::getSchool(true, $authId, true);
                if (!empty($schoolArr)){
                    $schoolIds = implode(',', array_keys($schoolArr));
                    $schoolList = XhschoolInfo::find([
                        'conditions' => "bDelete = 0 AND (iStatus = 1 OR iStatus = 2) AND iSchoolId in ({$schoolIds})",
                        'columns'    => 'iSchoolId',
                    ])->toArray();

                    $schools = array_column($schoolList, 'iSchoolId');
                    $schoolIdStr = implode(',', $schools);
                    $conditions  = " AND u.iSchoolId IN ({$schoolIdStr})";
                }
            }

            $schoolIds  = School::getPower();
            if (!$schoolIds) {
                return $this->sendErrorResponse(400, '无学校权限');
            } elseif ($schoolIds !== true) {
                $schoolIdStr = implode(',', $schoolIds);
                $conditions  = " AND u.iSchoolId IN ({$schoolIdStr})";
            }

            $sql = "SELECT 
                  u.iSchoolId AS iSchoolId,
                  CONCAT(SUBSTRING(u.sAdClsName, 1, 2), '级') AS grade,
                  c.receivable AS price,
                  SUM(c.receivable > 0) AS totalNum,
                  SUM(c.receivable > 0 AND c.receivable = c.received) AS payNum,
                  SUM(c.receivable > c.received AND c.received > 0) AS subPayNum,
                  SUM(c.receivable > 0 AND c.received = 0) AS notPayNum,
                  SUM(c.received > c.receivable) as overPay
                FROM XHCost_Charge AS c
                LEFT JOIN XHSys_User AS u ON c.userId = u.iUserId
                WHERE c.bDelete = 0 AND u.bDelete = 0 AND c.receivable > 0 AND c.`year` = '{$year}'
                  {$conditions}
                GROUP BY u.iSchoolid,grade,c.receivable";

            $data = Main::runSqlPage($sql);
            School::runName($data['rows'], ['iSchoolId' => 'sSchoolName']);
            School::runCode($data['rows'], ['iSchoolId' => 'sCode']);

            //处理学校编号
//            foreach ($data['rows'] as &$row) {
//                $row['sCode'] = 'XH' . substr(100000 + $row['iSchoolId'], 1, 5);
//            }
//            unset($row);
            return $return ? $data['rows'] : $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            if ($return) {
                throw new \Exception($e->getMessage());
            }
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
//        $type       = $this->request->getPost('type', 'int');
//        $chargeYear = $this->request->getPost('chargeYear', 'string');
//        if (!$chargeYear) {
//            return $this->sendErrorResponse(400, '缺少年份');
//        }
//        try {
//            $schoolIds = School::getPower();
//            if (!$schoolIds) {
//                return $this->sendErrorResponse(400, '无学校权限');
//            }
//            switch ($type) {
//                case 1:
//                    $priceField = 'c.iSumDues';
//                    break;
//                case 2:
//                    $priceField = 'c.iSerCost';
//                    break;
//                case 3:
//                    $priceField = 'c.iDevCost';
//                    break;
//                case 4:
//                    $priceField = 'c.iDeposit';
//                    break;
//                case 5:
//                    $priceField = 'c.iDevCost + c.iDeposit';
//                    break;
//                default: return $this->sendDataGridError('不支持该项目查询');
//            }
//            $delayYear = $chargeYear + 1;
//            $builder = $this->modelsManager->createBuilder()
//                ->columns([
//                    'u.iSchoolId as iSchoolId',
//                    'CONCAT(SUBSTRING(u.sAdClsName, 1, 2), "级") as grade',
//                    "IFNULL({$priceField}, 0) as price",
//                    'count(c.iSumDues) as totalNum',
//                    'sum(IFNULL(c.iSumCost, 0) > 0) as payNum',
//                    'sum(IFNULL(c.iSumCost, 0) < IFNULL(c.iSumDues, 0)) as notPayNum',
//                    "IFNULL(sum(c.tChargeTime > '{$delayYear}'), 0) as delayNum"
//                ])
//                ->from(['c' => '\\Admin\\Models\\cost\\XhcostStudcharge'])
//                ->leftJoin('\\Admin\\Models\\user\\XhsysUser', 'c.iStudId = u.iUserId', 'u')
//                ->where('u.bDelete = 0 AND c.bDelete = 0 AND c.iChargeYear = :chargeYear:', ['chargeYear' => $chargeYear])
//                ->groupBy(['u.iSchoolId', 'SUBSTRING(u.sAdClsName, 1, 2)', "IFNULL({$priceField}, 0)"]);
//            if ($schoolIds !== true) {
//                $builder->andWhere('u.iSchoolId IN ({schoolIds:array})', ['schoolIds' => $schoolIds]);
//            }
////            if ($chargeYear) {
////                $builder->andWhere('c.iChargeYear = :chargeYear:', ['chargeYear' => $chargeYear]);
////            }
//            $data = Main::runBuilderPage($builder);
//            Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName']);
//
//            //处理学校编号
//            foreach ($data['rows'] as &$row) {
//                $row['schoolNo'] = 'XH' . substr(100000 + $row['iSchoolId'], 1, 5);
//            }
//            unset($row);
//            return $this->sendJsonResponse($data);
//        }
//        catch (\Exception $e) {
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
    }

    /**
     * 导出收费报表2
     *
     * @return string
     *
     * create by ck 20181122
     */
    public function exportChargeStatsAction()
    {
        try {
            $data  = $this->getChargeStatsAction(true);
            $title = Template::getXmlFields('Cost_ChargeStats2');
            $data = Tool::runExcelData($title, $data);
            $fileName = '收费统计2';
            $this->view->disable();
            Tool::exportExcelOnline($fileName, $title, $data, 'xlsx', ['autoWidth' => true]);
        }
        catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

//    /**
//     * 新增收费界面
//     *
//     * @return bool|string
//     *
//     * create by ck 20170810
//     */
//    public function studChargeCreateAction()
//    {
//        $this->view->pick('cost/studChargeCreate');
//        Assets::datetimePicker('js/cost/studChargeCreate.js');
//        $studId = $this->request->getQuery('studId', 'int');
//        if (!$studId){
//            return $this->sendViewError('缺少用户参数！');
//        }
//        $this->view->setVars([
//            'Form' => Template::createForm('Cost_StudCharge')
//        ]);
//        return true;
//    }
//
//    /**
//     * 新增缴费记录
//     *
//     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     *
//     * create by ck 20170725
//     */
//    public function createStudChargeAction()
//    {
//        $data = $this->request->getPost();
//        if(!$data['iStudId']){
//            return $this->sendErrorResponse(400, '缺少学生id！');
//        }
//        if(!$data['iChargeYear'] || $data['iChargeYear'] > 2100 || $data['iChargeYear'] < 2000){
//            return $this->sendErrorResponse(400, '缴费年度错误！');
//        }
//        if(!$data['iSumCost']){
//            return $this->sendErrorResponse(400, '缴费总额有误！');
//        }
//        $checkCharge = XhcostStudcharge::count([
//            'conditions'    => 'bHistory = 0 AND bDelete = 0 AND iChargeYear = :chargeYear: AND iStudId = :studId:',
//            'bind'          => ['chargeYear' => $data['iChargeYear'], 'studId' => $data['iStudId']]
//        ]);
//        if($checkCharge){
//            return $this->sendErrorResponse(400, '该缴费年度下已有记录！');
//        }
//        if($data['iSerYear']){
//            $data['tExpireTime'] = date('Y-m-d H:i:s', strtotime($data['tChargeTime'] . " + {$data['iSerYear']} year"));
//        }
//        $charge = new XhcostStudcharge();
//        $charge->assign($data);
//        if (!$charge->save()) {
//            return $this->sendErrorResponse(500, '保存失败！');
//        }
//        return $this->sendSuccessResponse('缴费成功！');
//    }


//    /**
//     * 费用拆分页面
//     *
//     * @return bool|string
//     *
//     * create by ck 20170810
//     */
//    public function studChargeSplitAction()
//    {
//        $this->view->pick('cost/studChargeSplit');
//        Assets::importJs('js/cost/studChargeSplit.js');
//        $id = $this->request->getQuery('id', 'int');
//        if (!$id){
//            return $this->sendViewError('缺少参数！');
//        }
//        $chargeInfo = XhcostStudcharge::findFirst($id);
//        if (!$chargeInfo){
//            return $this->sendViewError('找不到该记录！');
//        }
//        if (!$chargeInfo->bImport){
//            return $this->sendViewError('非导入数据无法拆分！');
//        }
//        $this->view->setVars([
//            'Form'       => Template::createForm('Cost_StudCharge'),
//            'chargeInfo' => $chargeInfo
//        ]);
//        return true;
//    }
//
//    /**
//     * 拆分费用
//     *
//     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     *
//     * create by ck 20170810
//     */
//    public function splitStudChargeAction()
//    {
//        $data = $this->request->getPost();
//        if (!$data['iCCId']){
//            return $this->sendErrorResponse(400, '缺少缴费ID！');
//        }
//        $charge = XhcostStudcharge::findFirst($data['iCCId']);
//        if (!$charge){
//            return $this->sendErrorResponse(500, '找不到该记录！');
//        }
//        $charge->assign($data);
//        if ($data['iSerYear']){
//            $charge->tExpireTime = date('Y-m-d H:i:s', strtotime($charge->tChargeTime . " + {$data['iSerYear']} year"));
//        }
//        if (!$charge->save()) {
//            return $this->sendErrorResponse(500, '保存失败！');
//        }
//        return $this->sendSuccessResponse('拆分成功！');
//    }


    /**
     * 将学生转移到其它学校
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by sqb 20190103
     */
    public function transferStudentAction()
    {
        $students = $this->request->getPost('students');
        $schoolId = $this->request->getPost('schoolId');
        $year = $this->request->getPost('year');

        $this->db->begin();
        foreach ($students as $student) {
            if ($student['reason'] != '该账号学校不匹配') {
                continue;
            }

            $userId = $this->getStudIdByCode($student['code'], null);
            //导入费用
            try {
                Charge::importDetail(intval($year), intval($userId), floatval($student['receivable']), [
                    'serviceStart' => $student['serviceStart'],
                    'serviceEnd' => $student['serviceEnd'],
                ]);
            } catch (XhException $e) {
                $errorUser[] = [
                    'name' => $student['name'],
                    'code' => $student['code'],
                    'reason' => '保存失败：' . $e->getMessage()
                ];
                continue;
            }

            $userObj = Charge::getUserInfo($userId);
            $beforeSchoolId = $userObj->iSchoolId;

            //记录之前学校所缴
            $sql = "update XHCost_ChargeDetail set iSchoolId = {$beforeSchoolId} where bDelete = 0 and iSchoolId is null";
            $result = $this->db->execute($sql);
            if (!$result) {
                $this->db->rollback();
                return $this->sendSuccessResponse('操作失败');
            }

            //记录学生转学状态
            $schoolObj = Charge::getSchoolInfo($beforeSchoolId);
            $stage = $schoolObj->iStage;
            $userCreateTime = $userObj->tCreateDate;
            $startYear = '20'.substr($userObj->sAdClsName, 0, 2);

            //查询转学记录，没有则初始化
            $history = XhsysUserHistory::find([
                'conditions' => 'iUserId = :userId:',
                'bind' => ['userId' => $userId],
                'order' => 'iId desc',
                'limit' => 1
            ]);

            if (empty($history->toArray())) {
                $userHistory = new XhsysUserHistory();
                $userHistory->iUserId = $userId;
                $userHistory->iYear = $startYear;
//                $userHistory->sGrade = substr($userObj->iGradeCode, 0, 1);
                $userHistory->sGrade = $stage;
                $userHistory->tUserCreateTime = $userCreateTime;
                $userHistory->tOutTime = date('Y-m-d H:i:s');
                $userHistory->iSchoolId = $userObj->iSchoolId;
                $userHistory->iStatus = 1;
                if (!$userHistory->save()) {
                    $this->db->rollback();
                    return $this->sendSuccessResponse('操作失败');
                }
            }

            $gradeNow = Charge::getSchoolInfo($schoolId)->iStage;
            $userNow = new XhsysUserHistory();
            $userNow->iUserId = $userId;
            $userNow->iYear = date('Y');
            $userNow->sGrade = $gradeNow;
            $userNow->tUserCreateTime = date('Y-m-d H:i:s');
            $userNow->tInTime = date('Y-m-d H:i:s');
            $userNow->iSchoolId = $schoolId;
            if (!$userNow->save()) {
                $this->db->rollback();
                return $this->sendSuccessResponse('操作失败');
            }

            $user = XhsysUser::findFirst([
                'conditions' => 'sLogonName = :code:',
                'bind' => ['code' => $student['code']]
            ]);
            $user->iSchoolId = $schoolId;
            $user->bHistory = 0;
            $user->sAdClsName = $student['class'];

            if (!$user->save()) {
                return $this->sendErrorResponse(400, '操作失败');
            }
        }

        if ($errorUser) {
            $this->db->rollback();
            return $this->sendSuccessResponse('操作失败');
        }

        $this->db->commit();
        return $this->sendSuccessResponse('操作成功');
    }

    /**
     * 调整服务时间
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by sqb 20190221
     */
    public function serviceTimeAdjustAction()
    {
        $startTime = $this->request->getPost('serviceStart', 'string');
        $endTime = $this->request->getPost('serviceEnd', 'string');
        $ids = $this->request->getPost('ids', 'string');

        $this->db->begin();
        try {
            CostChargeDetail::find([
                'conditions' => 'bDelete = 0 and userId in ('.implode(',', $ids).')'
            ])->update([
                'serviceStart' => strtotime($startTime),
                'serviceEnd' => strtotime($endTime)
            ]);

            XhsysUserstud::find([
                'conditions' => 'bDelete = 0 and iUserId in ('.implode(',', $ids).')'
            ])->update(['iExpireTime' => strtotime($endTime)]);

            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }
}

